我制作了这个程序,它的工作正是我想要的,但它应该在我输入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;
}
答案 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))