[英]Can someone explain me whats wrong with finding total part in this code
每当我运行它时,我都会得到类似“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 中返回一个 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'));
我认为在将新添加的元素添加到数组中后,您应该增加计数器 z 。 1) 通过 scanf 获取值 2) 通过使用 vet[z] 3) 增加 z。
当您的代码达到总和时,它将尝试访问填充有其他一些值的内存段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.