输出是这样的 (奇数: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;
}
答案 0 :(得分:0)
您输出所有的奇数,然后将ctr设置为2并输出所有的偶数。
答案 1 :(得分:0)
这样做时,您需要小心在单独的循环中打印偶数和奇数的列表。
我假设您输入的内容不超过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