使用while循环打印偶数和奇数系列

时间:2016-03-09 00:38:58

标签: c++

我知道我错过了一些非常简单的东西,但我似乎无法使用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
}

1 个答案:

答案 0 :(得分: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
}