2017-05-22 441 views
-3

处理这个问题,我卡住了。我知道这应该是一个简单的修复,但我不确定。我相信它被困在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); 
     } 

    } 
+5

'如果(i = 5)'?不应该是'if(i == 5)'? –

回答

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

正确的答案是关闭:错字。 – user4581301

+0

一个简单的答案,就像我想的那样。感谢您的解释。这说得通。 – alittlebrownsmurph

0

您应该使用

if (i == 5) 

代替:

if (i = 5) 
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