2013-11-22 34 views
0

下面是一個代碼:(whyerror1.exe)'如果' 裏面的 '爲' 導致遊戲崩潰 - C語言

#include <stdio.h> 
#include <stdlib.h> 
int i, n, health=100; 
int main(void) 
{ 
    for (i=0; i<1; i++) 
    { 
     printf("health: %d\n",health); 
     printf("There is meat on the ground.\n"); 
     printf("Will you eat it?\n"); 
     printf("1: yes 2: no\n"); 
     scanf("%d", n); 
     if(n==1) { 
         system("cls"); 
         printf("Ate it. \n"); 
         printf("There is no people, so it is safe to eat. \n"); 
         printf("Health is increased.\n"); 
         system("pause>nul"); 
         system("cls"); 
         } 
     else if(n==2) { 
         system("cls"); 
         printf("Didn't ate it. \n"); 
         printf("More hunger, less health. \n"); 
         system("pause>nul"); 
         system("cls"); 
         } 
     else { 
        printf("select between 1 and 2. \n"); 
        system("pause>nul"); 
        system("cls"); 
        i=-1; 
     } 
    } 
} 

結果:whyerror1.exe停止工作。 這是怎麼回事? 我已經嘗試過選擇其他數字。我嘗試了任何數字! Plz幫助!

+1

CFR xorguy的答案在這裏下。作爲一個方面說明,你不應該在循環內部操作for循環的索引。其實這是一個典型的情況,你根本不應該使用for循環,但'while'或'do ... while' –

+0

@Bartdude哦,我不知道。那麼,它確實有效,但使用while將會更好。謝謝你告訴我。 – user3022392

+0

@Bartdude在這個(以及很多)案例中,我同意不應該在循環中操作'for'索引,但是,在這種情況下,您絕對不應該過度超越。我認爲最近有一個我認爲很合理的例子是用於解析命令行參數的(for =(i = 1; i mah

回答

4
scanf("%d", n); 

應該是:

scanf("%d", &n); 
+0

哈哈,居然沒有想到!非常感謝你! – user3022392