2015-03-08 64 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