【发布时间】:2016-01-14 00:01:42
【问题描述】:
我为杂货店编写了这段代码。这段代码对我来说非常有意义。但是,我不断收到逻辑错误。每次用户输入账单然后按 -1 退出时,他都会返回到主菜单。当用户按下选项 2 退出程序时,程序没有退出,他出于某种原因回到案例 1。请你帮助我好吗?谢谢!
#include <stdio.h>
int main(void){
double prices[7];
prices[0]=2.55;
prices[1]=12.07;
prices[2]=2.00;
prices[3]=0.55;
prices[4]=5.35;
prices[5]=8.65;
prices[6]=2.55;
int choice;
int productCode;
int quantity;
char stop[3];
int compare;
double price;
double totalPrice=0;
do{
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
choice=scanf("%d", &choice);
switch(choice){
case 1:{
do{
printf("\nEnter product code: ");
scanf("%d",&productCode);
printf("\nEnter quantity of product: ");
scanf("%d",&quantity);
price=prices[productCode]*quantity;
totalPrice=totalPrice+price;
printf("\nTo stop entering products enter -1.. to continue press any other character ");
scanf("%s", &stop);
compare=strcmp(stop, "-1");
}while(compare!=0);
break;
}
case 2: break;
default: printf("\nInvalid choice");
}
}while(choice!=2);
getchar();
return 0;
}
【问题讨论】:
-
调试:添加断点,显示变量值,跟踪执行。
-
你应该使用return而不是中断,在这种情况下“case 2:”应该返回0来结束程序
-
“每次用户输入账单然后按-1退出时,他都会被带回主菜单”。
case块中的break将退出封闭的switch。在您的情况下,它将通过评估while(choice!=2)来继续do循环。该条件成立,因为choice是1。因此主菜单再次打印出来。 -
@kaylum 问题不在于重新打印主菜单。它是关于我按数字 2 退出但程序没有退出的事实。相反,它又回到了案例 1。感谢您尝试提供帮助! :)
-
您还应该检查产品代码是否在
price=prices[productCode]*quantity;之前的范围内。