【发布时间】:2019-09-30 16:55:13
【问题描述】:
我正在尝试创建一个程序,该程序接受用户使用的加仑数和行驶里程数的三个油箱的输入,以完成一项任务。我遇到的问题是 for 循环要么没有正确地将输入中处理的两个值划分为第三个值(每加仑平均英里数),要么程序没有正确处理输入。但是我对此仍然很陌生,所以我不确定问题出在哪里。
for(i = 1; i <= 3; ++i)
{
/* Define calculations */
/* ------------------- */
ave_miles = miles / gallons;
total_miles = total_miles + miles;
total_gallons = total_gallons + gallons;
total_ave_miles = total_miles / total_gallons;
/* Propmpt user for miles and gallons used and calculate miles per gallon. */
/* ----------------------------------------------------------------------- */
printf("Enter the number of gallons used for Tank #%i: ", i);
scanf("%f", &gallons);
while ( (c = getchar() != '\n') && c != EOF);
printf("Enter the number of miles driven: ");
scanf("%f", &miles);
while ( (c = getchar() != '\n') && c != EOF);
printf("*** The miles per gallons for this tank is %.1f\n\n", ave_miles);
} /* end for loop */
/* Display and calculate the total miles per gallon for the three tanks. */
printf("Your overall average of miles per gallon for three tanks is %.1f\n\n", total_ave_miles);
printf("Thank You for using the program. Goodbye.\n");
} /* end main */
【问题讨论】:
-
欢迎来到 Stack Overflow!请edit您的代码将其减少为您的问题的minimal reproducible example。您当前的代码包含许多与您的问题无关的内容 - 一个最小样本通常看起来类似于一个好的单元测试:只执行一项任务,并为可重复性指定输入值。
-
关于;
/* Define calculations */ /* ------------------- */ ave_miles = miles / gallons; total_miles = total_miles + miles; total_gallons = total_gallons + gallons; total_ave_miles = total_miles / total_gallons;这些可执行语句有误。它们应该是 cmets,而不是可执行代码。 -
这两个语句:
while ( (c = getchar() != '\n') && c != EOF);不需要,因为输入格式说明符%f将占用前导“空白” -
旁白:您不需要此处的换行删除代码。
scanf的大多数格式说明符会自动过滤前导空格,因此您只需要两个scanf语句即可。例外是%c和%[]和%n。 -
一般来说,在变量被初始化/分配一些值之前,不能对变量执行数学运算