我第一次尝试用 C 编程,并将其应用于一些具体的东西......
我正在创建的解决问题的程序处理一个while循环。该程序的目标是计算一组卡车每加仑的平均英里数。我希望它在输入 -1 作为消耗的加仑数后立即终止,但我必须输入两次,一次输入加仑数,一次输入英里数。我发现这个输入实际上被用作结果计算的一部分。这是代码:
#include <stdio.h>
int main()
{
int tanks, miles;
float gallons = 0, average = 0, miles_per_gallon = 0;
tanks = 0;
while (gallons != -1) {
tanks += 1;
miles_per_gallon = (float)miles / gallons;
average = average + miles_per_gallon;
printf("The miles / gallon for this tank was %.3f\n",
miles_per_gallon);
printf("Enter the gallons used (-1 to end): ");
scanf("%f", &gallons);
printf("Enter the miles driven: ");
scanf("%d", &miles);
}
average /= tanks;
printf("The overall average miles/gallon was %.3f", average);
return 0;
}
这是一些示例输出:
C:\>gallons
Enter the gallons used (-1 to end): 12.3
Enter the miles driven: 700
The miles / gallon for this tank was 56.911
Enter the gallons used (-1 to end): 13.4
Enter the miles driven: 666
The miles / gallon for this tank was 49.701
Enter the gallons used (-1 to end): 17.3
Enter the miles driven: 644
The miles / gallon for this tank was 37.225
Enter the gallons used (-1 to end): 15.5
Enter the miles driven: 777
The miles / gallon for this tank was 50.129
Enter the gallons used (-1 to end): -1
Enter the miles driven: -1
The miles / gallon for this tank was 1.000
The overall average miles/gallon was 38.993
谢谢你的帮助。