繁体   English   中英

为什么在第二次左右调用后我的数组元素不显示?

[英]Why won't an element of my array display after being called the second or so time?

我在 C 编程项目的销售点计划中遇到问题。 问题是,每当我尝试在数组中第二次左右调用第一个订单时,它都不会出现。 但是,如果我要从该数组中调用不同的元素/顺序大约一秒钟,它就会出现。 我不明白为什么会这样。 这里是它的 function:

int orderTaking()
{
    int i, j, cash, cashChange, order, option, choice, additionalChoice, quantity, total, finalTotal, additionalPrice = 0;
    int price[20] = {20 , 80 , 85 , 90 , 90 , 150 , 100 , 120 , 130 , 120 , 150, 120 , 110, 150, 160, 60, 60, 30, 20, 15};
    int receipt[20];
    char orders[21][30] = { "Tiny Burger", "Jumbo Burger", "Turkey Burger", "Chicken Burger", "BBQ Burger" , "Banquet Burger" , "Chili Burger" , "California Burger" , "Juicy Lucy" , "Rice Burger" , "Salmon Burger" , "Slopper" , "Slug Burger" , "Veggie Burger" , "Teriyaki Burger" , "Big Fries" , "Mojos" , "Large Drinks" , "Water" , "Extra Cheese" };
    char orderChoice;

    i = 1;
    while(1)
    {
        printf("\n\tWhat is your order? ");
        scanf("%d", &choice);
        printf("\n\tYou chose %s!", orders[choice - 1]);
        printf ("\n\tEnter quantity of order: ");
        scanf("%d", &quantity);

        receiptInfo[i].quantity = quantity;
        receiptInfo[i].order = choice;
        receipt[i] = choice;

        total = (price[choice -1] * quantity);
        additionalPrice += total;
        receiptInfo[i].receiptTotal = total;
        i++;

        printf("\n\tYour total is %d PHP", additionalPrice);
        printf("\n\tWould you like to order again? (Y/N): ");
        scanf("%s", &orderChoice);
        if (orderChoice == 'Y') 
            continue;
        else if (orderChoice == 'N')    
            break;  
        else 
            printf("\n\tInvalid Input, Please try again!");
            additionalPrice = 0;
            continue;
    }

您为数组使用了错误的起始索引。 一个元素 [在索引0处]永远不会被填充。

你开始:

i = 1;

将其更改为:

i = 0;

更新:

所以我只是尝试将i = 1更改为i = 0,该元素仍然不会出现。

如果不发布您的整个程序,就很难确定哪里出了问题。 此外,您发布的内容不会编译干净,因为没有return语句。 而且,您有许多未使用的变量。

我会用-Wall -O2重新编译并修复所有警告/错误。

但是,我确实注意到的一件事是:

if (orderChoice == 'Y')
    continue;
else if (orderChoice == 'N')
    break;
else
    printf("\n\tInvalid Input, Please try again!");
    additionalPrice = 0;
    continue;

但是,缩进具有误导性。 正确完成我们有:

if (orderChoice == 'Y')
    continue;
else if (orderChoice == 'N')
    break;
else
    printf("\n\tInvalid Input, Please try again!");
additionalPrice = 0;
continue;

这可能不会改变结果,但我相信你的意思是:

if (orderChoice == 'Y')
    continue;
else if (orderChoice == 'N')
    break;
else {
    printf("\n\tInvalid Input, Please try again!");
    additionalPrice = 0;
    continue;
}

进一步清理/简化:

if (orderChoice == 'Y')
    continue;
if (orderChoice == 'N')
    break;
printf("\n\tInvalid Input, Please try again!");
additionalPrice = 0;

因此,如果给出任何无效输入,则作为运行总和的additionalPrice价格将重置为零。 这真的是你想要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM