简体   繁体   English

如何将输出数字除以奇数和偶数?

[英]How can I divide the output numbers in odd and even numbers?

The output is like this (odd numbers: 1even numbers: 2odd numbers: 3even numbers: 4odd numbers: 5even numbers: 6odd numbers: 7even numbers: 8odd numbers: 9even numbers: 10)输出是这样的(奇数:1偶数:2奇数:3偶数:4奇数:5偶数:6奇数:7偶数:8奇数:9偶数:10)

Output should be (odd numbers: 1 3 5 7 9, even numbers: 2 4 6 8 10)输出应该是(奇数:1 3 5 7 9,偶数:2 4 6 8 10)

int main() {
  int num1,ctr=1,modu,even,odd;
  cout<<"enter a number";
  cin>>num1;

  do {
    if (ctr%2 == 0) {
      cout<<"even numbers: "<<ctr;
      ctr++;
    } else {
      cout<<"odd numbers: "<<ctr;
      ctr++;
    }
  }
  while(ctr<=num1);
  return 0;
}

你输出所有的奇数,然后将ctr设置为2,输出所有的偶数。

In doing this, you need to be careful to print the list of even numbers and odd numbers in separate loops.在执行此操作时,您需要小心地在单独的循环中打印偶数和奇数列表。

I have assumed that you will have no more than 10 inputs.我假设您的输入不超过 10 个。 If you will have more, then you need to increase the constant 'limit'.如果您将拥有更多,那么您需要增加恒定的“限制”。

#include <iostream>

using namespace std;

int main() {
    const int limit = 10;
    int array[limit];
    int num1;
    int ctr = 0;

    while(ctr < limit ) {
        cout << endl << "Please enter a number" << endl;
        cin >> num1;
        array[ctr] = num1;
        ++ctr;
    }

    // print odd numbers
    cout << "Odd numbers: ";
    for(int i = 0; i < limit; i++) {
        if(array[i] %2 == 1) {
            cout << " " << array[i];
        }
    }
    // print even numbers
    cout << "  Even numbers: ";
    for(int i = 0; i < limit; i++) {
        if(array[i] %2 == 0) {
            cout << " " << array[i];
        }
    }
    cout << endl;

    return 0;
}
Output:

Odd numbers:  1 3 5 7 9  Even numbers:  2 4 6 8 10

Process finished with exit code 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM