对于If Else声明

时间:2017-05-22 00:05:13

标签: c++

解决这个问题,我被困住了。我知道这应该是一个简单的修复,但我不确定。我相信它停留在for循环中所以可以继续重复,但我不知道如何解决它。我尝试添加printf和scanf函数,但是没有用。添加一会儿。那没用。我显然使这件事比它需要的更难。

    int i;

    for (int i = 0; i <= 10; i++)
    {
        if (i = 5)

        {
            printf("\nFive is my favorite number\n");
        }
        else
        {
            printf("\n%di is \n", i);
        }

    }

3 个答案:

答案 0 :(得分:2)

这是因为您总是将i重新分配给5.您希望比较 i代替5.

int i;

for (int i = 0; i <= 10; i++)
{
    if (i == 5) // you need to do a comparison here
    {
        printf("\nFive is my favorite number\n");
    }
    else
    {
        printf("\n%di is \n", i);
    }
}

答案 1 :(得分:0)

你应该使用

if (i == 5)

而不是:

if (i = 5)

答案 2 :(得分:0)

这是一个非常常见的错误,新程序员会遇到困难:

if (i = 5) // this is not a comparison but assignment and as you can see

//此条件始终为真

要纠正它是:

if (i == 5)
    // Do some stuff

避免这种容易出错的错误有一个很好的魔力就是扭转比较:

if ( 5 = i) // here the compiler will catch this error: assigning a value to a constant

if( 5 == i) // correct
相关问题