我从2天前的一本书中学习c ++,其中一个练习令我感到困惑。我觉得我做得对,但这本书没有教我这个。有人可以告诉我如何处理我的代码,使其只打印(用户输入的)和b(用户输入)的偶数。
int a, b;
cout << "What number would you like to start counting at?" << endl;
cin >> a;
cout << "What number would you like to end at?" << endl;
cin >> b;
while (a <= b){
if (a % 2 == 0){
cout << a << endl;
a++;
}
}
return 0;
答案 0 :(得分:3)
即使不均匀,您也必须提高a
的值:
int a, b;
cout << "What number would you like to start counting at?" << endl;
cin >> a;
cout << "What number would you like to end at?" << endl;
cin >> b;
while (a <= b){
if (a % 2 == 0){
cout << a << endl;
}
a++;
}
return 0;
答案 1 :(得分:1)
如果a
是偶数,那么您的代码只会增加a
,这样做不好,您希望a++
循环中的while
,但if a is even
之外的{{1}} {1}}