gpt4 book ai didi

c - 需要基本食品银行计划帮助

转载 作者:行者123 更新时间:2023-11-30 17:27:47 25 4
gpt4 key购买 nike

我在下面的代码中遇到了选项 2(即请求)的问题。每次我打印出请求表时,它都会给我一个随机的高数字,而不是显示用户输入的待处理请求。有人可以帮我找到问题吗?该代码应与选项 1 类似,但如果请求相同,则不应将用户输入相加。示例输出:

1
Milk 20
1
Milk 20
2
Milk 10
2
Milk 5
4
Donations:
Milk 40
Requests:
Milk 10
Milk 5

这是我的代码

int main() {

int don_count=0, don_amt[100], found, i, don_quant, option, req_count=0, req_amt[100],req_quant;

char word[20], don_inv_type[100][20], req_word[20], req_inv_type[100][20];

printf("Welcome to the food bank program!);
printf("1.Enter a Donation\n2.Enter a Request\n3.Fulfill the earliest Request\n4.Print status report\n5.Exit\n");
scanf("%d", &option);

while (option != 5) {

// Execute a deposit.
if (option == 1) {
scanf ("%s", word);
scanf ("%d", &don_quant);
found = -99;
for (i=0;i<don_count; i++){
if (strcmp(don_inv_type[i], word)==0)
found = i;
}
if (found == -99){
strcpy(don_inv_type[i],word);
don_amt[i] = don_quant;
don_count ++;
}
else
don_amt[found] += don_quant;
}

else if (option == 2) {
scanf ("%s", req_word);
scanf ("%d", &req_quant);
req_count++;
for(i=0; i<req_count; i++)
{
strcpy(req_inv_type[i],req_word);
req_amt[i] += req_quant;
}
}

else if (option == 3) {


}

else if (option == 4) {
printf("Donations:\n");
for(i=0;i<don_count;i++){
printf("%8s", don_inv_type[i]);
printf("%5d\n", don_amt[i]);
}
printf("Requests: \n");
for(i=0;i<req_count;i++){
printf("%8s", req_inv_type[i]);
printf("%5d\n", req_amt[i]);
}


}

else if (option == 5) {
printf(" Thanks bye");

}

// Reprompt the menu.
printf("1.Enter a Donation\n2.Enter a Request\n3.Fulfill the earliest Request\n4.Print status report\n5.Exit\n\n");
scanf("%d", &option);
} // end while

system("PAUSE");
return 0;
} // end main

最佳答案

您永远不会初始化req_amt,因此req_amt[i] += req_quant只是将req_quant添加到之前这些内存位置的任何垃圾中.

您需要执行以下操作:

int req_amt[100] = {0};
^^^^^^ <--- Add this

或以其他方式手动初始化元素。

关于c - 需要基本食品银行计划帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26268187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com