为什么此代码不适用于偶数和?

时间:2019-06-12 06:39:59

标签: c++11

我正在尝试查找偶数和,但它不起作用。删除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;
}

当我输入数字时,什么地方都没有。

1 个答案:

答案 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;
}