我在C中循环时无法弄清楚

问题描述

我是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);
}

解决方法

这不是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,以便编写简单的输入函数以在学习函数输入后立即读取一行,一个整数和一个double值,这应该相差不远。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...