我正在尝试查找偶数和,但它不起作用。删除if
条件后,它仅适用于整数和。
main()
{
int number, sum, upperlimit;
number=1;
sum=0;
std :: cout << "Please enter the number of digits:";
std :: cin >> upperlimit;
while(number<=upperlimit)
{
if(number%2==0)
{
sum = sum + number;
number = number + 1;
}
}
std :: cout << "sum of 1st " << upperlimit <<" Even digits is:" << sum;
}
当我输入数字时,什么地方都没有。
答案 0 :(得分:1)
if(number%2==0)
{
sum = sum + number;
number = number + 1;
}
在number+=1
中具有if
条件意味着这仅在数字为偶数的情况下才会继续。因此,举例来说,一旦您到达1
,它将永远保持1
的地位。
main()
{
int number, sum, upperlimit;
number=1;
sum=0;
std :: cout << "Please enter the number of digits:";
std :: cin >> upperlimit;
while(number<=upperlimit)
{
if(number%2==0)
{
sum = sum + number;
}
number = number + 1;
}
std :: cout << "sum of 1st " << upperlimit <<" Even digits is:" << sum;
}