int main() {
int miles_ran, i;
float miles_ran_time, avg_time, sum;
//ask's user for how many miles they ran
printf("How many miles did you run?\n");
scanf("%d", &miles_ran);
//ask's the user for each time that it took them to run each mile
//loop continues asking for each of their time depending on the number inputed above
for (i = 1; i <= miles_ran; i++){
printf("\nHow long did it take you to run mile #%d\n", i);
scanf("%d", &miles_ran_time);
}
printf("\nYour average time to run a mile is %.3f.\n", avg_time);
return 0;
}
我需要帮助才能获得用户输入的每个不同时间的平均值。我似乎无法弄清楚如何去做。例如,如果用户输入他们跑3英里,他们3英里的时间是10,10.5和9;平均值将达到9.83。
答案 0 :(得分:1)
简单总结您所读的所有时间并除以总里程:
sum = 0;
for (i = 1; i <= miles_ran; i++){
printf("\nHow long did it take you to run mile #%d\n", i);
scanf("%d", &miles_ran_time);
sum += miles_ran_time;
}
avg_time = sum / miles_ran;
答案 1 :(得分:0)
做自己的功课!
你是怎么想出你的9.83的?您将所有数字加在一起并除以里程数,因此您在代码中执行相同的操作。在循环中保持运行总和(sum + = miles_ran_time;)然后计算avg_time。
答案 2 :(得分:0)
您需要将时间相加并将它们除以里程数。
#include <stdio.h>
int main() {
int miles_ran, i;
float miles_ran_time, avg_time, sum;
float time = 0;
//ask's user for how many miles they ran
printf("How many miles did you run?\n");
scanf("%d", &miles_ran);
//ask's the user for each time that it took them to run each mile
//loop continues asking for each of their time depending on the number inputed above
for (i = 1; i <= miles_ran; i++){
printf("\nHow long did it take you to run mile #%d\n", i);
scanf("%f", &miles_ran_time);
time += miles_ran_time;
}
printf("\nYour average time to run a mile is %.3f.\n", time/miles_ran);
return 0;
}
答案 3 :(得分:0)
一些基本错误。请参阅下面的内联评论。
#include <stdio.h>
int main() {
int miles_ran=0, i=0; /* initialize your variables */
int c;
float miles_ran_time=0.0, avg_time=0.0, sum=0;
//ask's user for how many miles they ran
printf("How many miles did you run?\n");
scanf("%d", &miles_ran);
do { c=getchar(); } while ( c != '\n' && c != EOF ); /* flush input buffer after scanf */
//ask's the user for each time that it took them to run each mile
//loop continues asking for each of their time depending on the number inputed above
for (i = 1; i <= miles_ran; i++){
printf("\nHow long did it take you to run mile #%d\n", i);
scanf("%f", &miles_ran_time);
do { c=getchar(); } while ( c != '\n' && c != EOF ); /* flush input buffer after scanf */
sum += miles_ran_time; /* compute 'sum' from miles ran time */
}
avg_time = sum / miles_ran; /* compute average */
printf("\nYour average time to run a mile is %.3f.\n", avg_time);
return 0;
}
<强>输出:强>
$ ./bin/avg
How many miles did you run?
5
How long did it take you to run mile #1
10.1
How long did it take you to run mile #2
9
How long did it take you to run mile #3
9.5
How long did it take you to run mile #4
9.8
How long did it take you to run mile #5
9.7
Your average time to run a mile is 9.620.