2016-03-09 138 views
-1

我知道我錯過了一些真正簡單的東西,但我似乎無法使用while循環獲取打印出的奇數或偶數數字的行數或循環。此外,它不斷打印出「偶數是:」/「奇數是:」每個數字。使用while循環打印一系列的偶數和奇數

#include<stdio.h> 
#include <iostream> 

using namespace std; 


int main() 
{ 
    //declare variables 
    int number; 
    int n; 

    cout << "Enter value less than 100: "; 
    cin >> n; //take user input 


    while (n <= 100) //loop only if n equals 100 or less 
    { 
     for(number = n; number <= n; number++) //for loop to increment int value 
     { 
      if(number % 2 !=0) //determines if odd 
      { 
       cout << "The odd numbers are:" <<number << endl; //prints odd values 
      } 
     } 

     for(number = n;number <= n; number++) // for loop to increment int value 
     { 
      if(number % 2 ==0) //determines if even 
      { 
       cout <<"The even numbers are:" <<number <<endl; //prints even values 
      } 
     } 

     n++; 
    } 

    return 0; //end of program 
} 

回答

0

您可能希望這樣:

#include <iostream> 

using namespace std; 

int main() 
{ 
    //declare variables 
    int number; 
    int n; 

    cout << "Enter value less than 100: "; 
    cin >> n; //take user input 

    // print odd values 
    cout << "The odd numbers are:"; 
    for (number = n + 1 - (n % 2); number <= 100; number += 2) 
    { 
     cout << " " << number; 
    } 
    cout << endl; 

    // print even values 
    cout << "The even numbers are:"; 
    for (number = n + (n % 2); number <= 100; number += 2) 
    { 
     cout << " " << number; 
    } 
    cout << endl; 

    return 0; //end of program 
} 
+0

謝謝!這是一個任務,我們必須使用一個while循環或循環。 – user2814798

+0

這些'for'循環的初始化部分沒有變量聲明,所以你可以通過'initialize'替換'for(initialization; condition; proceed){statements;}'來將它們轉換爲while循環。 while(condition){語句;繼續;}' – MikeCAT