簡體   English   中英

如何將輸出數字除以奇數和偶數?

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

輸出是這樣的(奇數:1偶數:2奇數:3偶數:4奇數:5偶數:6奇數:7偶數:8奇數:9偶數: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,輸出所有的偶數。

在執行此操作時,您需要小心地在單獨的循環中打印偶數和奇數列表。

我假設您的輸入不超過 10 個。 如果您將擁有更多,那么您需要增加恆定的“限制”。

#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