每当我运行这个时,我都会得到类似“196875307”的总数,可以 有人告诉我它出了什么问题。这里我上传了整个代码。它说我的帖子主要是代码并添加更多细节,所以请原谅我输入这些不必要的东西XD
#include <stdio.h>
int room;
char name[20];
int i;
void main()
{
int answr,fc[6],z=0,tot;
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("\n *********");
printf("\n MENU CARD");
printf("\n *********\n\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\t%d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER
FOOD");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
printf("Enter the main menu function here");
break;
}
case 1:do
{
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf(" %d",&fc[z]);
z++;
tot=tot+fc[z];
printf("total so far is %d",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
}while((ans=='y')||(ans=='Y'));
printf("\nEnter your room number:");
scanf(" %d",&room);
printf("\nEnter your name:");
scanf(" %s",&name);
}
}
最佳答案
问题出在你的 do 循环上。您需要将 tot 初始化为 0,并使用用户输入的“食物代码”作为价格数组的数组索引。我没有看到您声明的“fc”数组有任何用处。此代码应该适用于 switch 语句中的情况 1。
请记住,C 中的 main 函数返回一个 int。
do {
tot = 0;
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8) {
printf("Invalid food code\n");
return -1; // main should return int in a C program
}
tot=tot+price[z-1];
printf("total so far is %d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
} while((ans=='y')||(ans=='Y'));
关于有人可以解释一下在这段代码中找到总部分有什么问题吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54154888/