gpt4 book ai didi

c - 我在结束 C 中的循环时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:42 25 4
gpt4 key购买 nike

我在学校学习 C。(我不要求任何人为我写这个)。

Assignment
This program will calculate the miles per gallon MPG for you for three tanks of gas after you have entered the gallons used and miles driven.

我可以让我的程序开始一个循环,但我不知道如何让它在运行 3 次后结束循环并给我 3 个坦克的平均 MPG。运行程序会给我平均值,但会一直询问。

#include <stdio.h>
int main(void) {
int miles;
float gallons = -1, mg, overall = 0, avg = 0;
while(gallons != 0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
}
return 0;
}

最佳答案

试试这个小改动。使用迭代器获取 3 个坦克的平均值。

修改喜欢

i=0;
while(i < 3) {
i++;

#include <stdio.h>
int main(void) {
int miles, **i=0;**
float gallons = -1, mg, overall = 0, avg = 0;
**while(i < 3)** {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
**i++;**
}
return 0;
}

关于c - 我在结束 C 中的循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com