【问题标题】:I cannot figure this while loop out in C我无法弄清楚这个while循环在C中
【发布时间】:2021-01-06 10:15:10
【问题描述】:

我是 C 编程新手,目前我正在为租赁业务解决问题。我试图询问什么类型的汽车,只有 3 种之间的选择,并计算一辆车的总租赁成本。我认为,我需要一个 while 循环,然后是几个 if 语句,但是,我目前能够编译代码,但是它只运行到输入第一个输入。任何指导都是有帮助的,我不是在寻找需要集中注意力的解决方案。 While 循环让我陷入循环;)

int type, daysRented, numberOfMiles, rentalTotal, totalRevenue = 0;

do{
    printf("Enter 0 for End, 1 for sports car, 2 for midsize, 3 for economy: ");
    scanf("%d\n", &type);
    
} while (type != 0);

printf("Enter days rented: ");
scanf("%d\n", &daysRented);
printf("Enter the number of miles: ");
scanf("%d\n", &numberOfMiles);

if (type == 1){
    rentalTotal = (daysRented * 75) + (numberOfMiles * 2);
    printf("%i\n", totalRevenue);
}

【问题讨论】:

    标签: c while-loop scanf do-while


    【解决方案1】:

    这不是while 循环,这是do/while 循环。您应该使用自动格式化程序缩进您的代码。当被要求调试缩进不佳的代码时,人们通常不高兴。

    这段代码实际上做的是运行提示符和scanf 行,直到提供了一个非零的数字,但提示符说它做了其他事情。

    你可能想要:

    while(1){
        do{
            type = -1;
            printf("Enter 0 for End, 1 for sports car, 2 for midsize, 3 for economy: ");
            scanf("%d", &type);        
        } while (type < 0 || type > 3);
        if (type == 0) break;
        // The rest of the stuff here ...
    }
    

    从而测试type是否在范围内,并在第一次运行后返回顶部。

    所以这个问题实际上比我要多。 scanf 格式行错误。在我从该格式说明符中删除 \n 后,循环会自行运行。我做了以下更改,它开始表现自己:

        scanf("%d", &type);        
        getc(stdin); /* throw away newline */
    

    我通常建议在学习函数输入后立即放弃 scanf,而改用简单的输入函数来读取行、整数和双精度数,这应该不会太远。

    【讨论】:

    • 谢谢乔希,你能详细说明你在哪里说提示说它做了其他事情吗?我相信这是我对循环最困惑的地方。
    • @jrochau 手工完成。看看它的作用。
    • 我有,但我没有看到我做错了什么。我已经实现了您建议的代码,并且我仍然能够编译它,但它与我之前的代码停滞在同一个位置。我输入第一轮数字 1、2 或 3,然后它就停止了。
    • @jrochau:啊。这也是一个scanf问题。
    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2014-02-16
    • 2013-11-12
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多