我正在从书中做以下程序,并且不知道我在哪里出错了。有人可以向我指出一些我错过的逻辑错误吗?
开发一个程序,输入用于每个容量的里程驱动和加仑。 该程序应计算并显示每个容器获得的每加仑英里数。在处理完所有输入信息后,程序应计算并打印所有储罐的每加仑组合里程数。
#include <stdio.h>
int main(void) {
int total = 0, count = 0;
float gallons_used, mpg, miles;
while(gallons_used != -1) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
total /= count;
printf("Average miles to the gallon was: %d\n", total);
return 0;
}
现在,看起来我的循环恰到好处,直到我退出它的值为-1,因为它仍然要求该坦克的里程数,显然输入它完全抛弃了总数。端。
答案 0 :(得分:2)
你可以使用无限循环并在以下情况下将其分解(如果gallons_used = -1
)for(;;) { // <-- infinite loop
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
if (gallons_used == -1)
break; // <-- exit the loop
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
答案 1 :(得分:1)
while(true) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
printf("Enter the miles driven: ");
scanf("%f", &miles);
if(gallons_used== -1 )break;
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
答案 2 :(得分:0)
#include <stdio.h>
int main(void) {
int total = 0, count = 0;
float gallons_used, mpg, miles;
while(gallons_used != -1) {
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
if (gallons_used < 0) // check gallons_used
break;
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
}
total /= count;
printf("Average miles to the gallon was: %d\n", total);
return 0;
}
答案 3 :(得分:0)
您正在使用gallons_used
未初始化。使用未初始化的变量会调用未定义的行为。在while
的条件表达式中进行比较之前,您需要先对其进行初始化。你可以这样做
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used); // Reading value for gallons_used
while(gallons_used != -1) {
printf("Enter the miles driven: ");
scanf("%f", &miles);
mpg = miles / gallons_used;
printf("Miles / gallon for this tank was %f\n", mpg);
total += mpg;
count++;
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons_used);
}