我是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);
}
答案 0 :(得分:2)
这不是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值,这应该相差不远。