谁能帮我看一下这个问题怎么解决?
#include<stdio.h>int main()
{
int counter = 0;/*输入次数*/
float liter, km, m, average;/*油量,里程,每公升油量的里程,所有油箱情况平均值*/
float total = 0;
printf("enter the liters used, -1 to end::");
scanf_s("%f", &liter);/*第一次输入油量*/
printf("enter the killometers driven:");
scanf_s("%f", &km);/*第一次输入里程*/
while (liter != -1){
m = km / liter;/*计算每公升跑了多少公里*/
counter += 1;/*输入次数计数*/
total += m;
printf("the km / liter is %f\n\n", m);
printf("enter the liters used, -1 to end:");
scanf_s("%f", &liter);
printf("enter the killometers driven:");
scanf_s("%f", &km);
}
average = total / counter;
printf("The overall average km / liter is:%f\n\n", average);/*输出总的平均每公升油量跑了多少公里*/
return 0;
}
书上的练习题,书上给出了结果,显示出来的结果是这样的:
Enter the gallons used (-1 to end): 12.8
Enter the miles driven: 287
The miles / gallon for this tank was 22.421875
Enter the gallons used (-1 to end): 10.3
Enter the miles driven: 200
The miles / gallon for this tank was 19.417475
Enter the gallons used (-1 to end): 5
Enter the miles driven: 120
The miles / gallon for this tank was 24.000000
Enter the gallons used (-1 to end): -1
The overall average miles/gallon was 21.601423
但是我写的那个while结构里边printf("enter the liters used, -1 to end:");输入-1之后还继续运行到了printf("enter the killometers driven:");这一步,我想是因为这个-1还没运行到条件liter != -1那里,所以会继续运行后边的。但是,我不知道怎么才能解决它,达到书上的那种效果,输入完-1之后就不会再出现多余的东西?