我正在尝试编写一个读取10个整数的程序,然后使用for循环查找并打印偶数和奇数整数的总和。
我看到For循环的先前帖子执行一次,但他们没有帮助我。谢谢你的帮助。
这是我的代码,
#include <iostream>
using namespace std;
int main()
{
int integer;
int even = 0;
int odd = 0;
int intcount = 0;
cout << "enter numbers" << endl;
cin >> integer;
for(; intcount <= 10; intcount++)
{
if((integer % 2) == 0)
{
even = even + integer;
}
else if((integer % 2) != 0)
{
odd = odd + integer;
}
}
cout << "Even sum: " << even << endl;
cout << "Odd sum: " << odd << endl;
return 0;
}
答案 0 :(得分:2)
cout<<"enter numbers"<<endl;
for(; intcount < 10; intcount++) // '< 10', not '<= 10' as you start with 0
{
cin>>integer; // <-- you should read numbers inside the loop
if(integer % 2 == 0 )
{
even += integer; // += is the same as 'even = even + integer'
}
else // no 'else if' needed, 'else' is enough
{
odd += integer;
}
}
cout<< "Even sum: " << even<< endl;
cout<< "Odd sum: " << odd<< endl;
答案 1 :(得分:0)
最好使用具有退出条件的while
循环并更改如下代码: -
while(1)
{
cout<<"Enter 0 to exit"<<endl;
cin>>integer; // <-- you should read numbers inside the loop
if( integer == 0 )
break;
else if(integer % 2 == 0 )
{
even += integer; // += is the same as 'even = even + integer'
}
else
{
odd += integer;
}
}