2015-03-08 44 views
0

我做了這個程序,它的工作只是我想如何,但它應該停止時,我鍵入x但它不 任何人可以告訴我爲什麼? ,如果有任何快捷方式或更小的方式鍵入此代碼? 在此先感謝。c編程語言:應用程序不會停止後輸入x

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main() 
{ 
    int meat[6]; 
    int i; 
    int total =0; 
    int avg; 
    char what[20]; 
    char end; 
    int days = 0; 
    char food[20]; 
    char drink[20]; 
    printf("what thing do u want to calculate the average of?(food/drink)\n"); 
    scanf(" %s", &what); 
    if(strcmp(what, "food")==0) 
    { 
     printf("what sort of food did u ate ?\n"); 
     scanf(" %s", food); 
    } 
    if(strcmp(what, "drink")==0) 
    { 
     printf("what sort of drink did u drank ?\n"); 
     scanf(" %s", drink); 
    } 
    for(i=0; i<6; i++)   
    { 
     days++; 
     if(strcmp(what, "food")==0) 
     { 
      printf("how many %s did u ate in day %d\n", food, i+1); 
     } 
     else if(strcmp(what, "drink")==0) 
     { 
      printf("how many liters of %s did u drank in day %d\n", drink, i+1); 
     } 
     scanf(" %d", &meat[i]); 
     total += meat[i]; 
     printf("if u want to continue type y\n"); 

     printf("type x if u want to finish\n"); 
     scanf(" %c", &end); 
     if((end = 'y')&&(i<5)) 
     { 
      continue; 
     } 
     else if(end = 'x' && strcmp(what, "drink")==0) 
     { 
      avg = total/days; 
      printf("\nyour average amount of liters of %s you had %d\t the total is %d\n", drink, avg, total); 
     } 
     else if(end = 'x' && strcmp(what, "food")==0) 
     { 
      avg = total/days; 
      printf("\nyour average amount of %s you had %d\t the total is %d\n", food, avg, total); 
     } 
     break; 
    } 
    if(strcmp(what, food)==0) 
    {   
     printf("\nyour average amount of %s you had is %d\t the total is %d\n", food, avg, total); 
    } 
    else if(strcmp(what, drink)==0) 
    {   
     printf("\nyour average amount of liters of %s you had is %d\t the total is %d\n", drink, avg, total); 
    } 

    return 0; 
} 

回答

1
else if(end = 'x' ... 

應該是:

else if(end == 'x' ... 

您使用==在if語句來測試平等。你已經在代碼中的幾個地方得到了這個,這是無意中執行的任務,而不是通過比較用戶輸入是否與特定字符相等來實現的。

更換===這裏:

else if(end = 'x' && strcmp(what, "drink")==0) 

這裏:

else if(end = 'x' && strcmp(what, "food")==0) 

和這裏:

if((end = 'y')&&(i<5)) 
+0

那些中的兩個,也'如果((端= 'y' 的)...)' – 2015-03-08 19:38:05

+0

x工作,但現在進入6天時它不會損害平均或總數 – 2015-03-08 19:48:29

+0

我懷疑你在這裏最後的比較還有一個邏輯錯誤,如果(strcmp(what,food)== 0)'和here' else if(strcmp(what,drink)== 0)',因爲這期望用戶爲他們吃的東西輸入了「食物」或「飲料」以及「食物」或「飲料」,這似乎並不是你要求用戶輸入的內容。我的猜測是,你想把這些比較中的「食物」和「飲料」分別轉換爲「食物」和「飲料」。 – 2015-03-08 19:58:14