xcode上C程序的逻辑错误

时间:2016-01-14 00:01:43

标签: c xcode logic

我已经为杂货店编写了这段代码..这段代码对我来说非常有意义。但是,我不断收到逻辑错误。每次用户输入账单然后按-1退出时,他都会被带回主菜单。当用户将选择2按到EXIT程序时,程序没有退出,并且由于某种原因他被带回到案例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;
}

1 个答案:

答案 0 :(得分:2)

而不是

choice=scanf("%d", &choice);

待办事项

scanf("%d", &choice);

scanf返回值为:

  

成功时,该函数返回参数的项数   列表已成功填写。此计数可以匹配预期的数量   由于匹配失败,读数,项目或更少(甚至为零)   错误,或文件结尾的范围。

     

如果发生读取错误或达到文件结尾   阅读,设置正确的指标(feof或ferror)。而且,如果有的话   在成功读取任何数据之前发生,返回EOF。

     

如果解释宽字符时发生编码错误,则   函数将errno设置为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");
    }

}