簡體   English   中英

有人可以解釋我在這段代碼中找到全部部分有什么問題嗎

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM