2017-05-22 496 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