我为一家杂货店编写了这段代码。这段代码对我来说非常有意义。但是,我不断收到逻辑错误。每次用户输入账单然后按-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;
}
最佳答案
代替
choice=scanf("%d", &choice);
做
scanf("%d", &choice);
scanf
返回值为:
On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.
If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ. http://www.cplusplus.com/reference/cstdio/scanf/
for (;;){
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
scanf("%d", &choice);
if(choice == 2 ){
break;
} else if(choice == 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);
} else {
printf("\nInvalid choice");
}
}
关于c - xcode上C程序的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779397/