我对这个问题很困惑。我的总距离计算不正确。我不确定这是因为我的循环设置不正确还是我做错了什么。我每次平均得到 -0
。我在平均计算之前打印了 printf("total distance = %lf , dailyflights = %d\n", totaldistance, dailyflights);
以确定它是 totaldistance
计算不正确,不是平均值。
所需输出的示例:
How many days has your dragon been practicing?
3
How many flights were completed in day #1?
2
How long was flight #1?
10.00
How long was flight #2?
15.00
Day #1: The average distance is 12.500.
How many flights were completed in day #2?
3
How long was flight #1?
9.50
How long was flight #2?
12.00
How long was flight #3?
13.25
Day #2: The average distance is 11.583.
How many flights were completed in day #3?
3
How long was flight #1?
10.00
How long was flight #2?
12.50
How long was flight #3?
15.00
Day #3: The average distance is 12.500.
我的代码:
//pre-processor directives
#include <stdio.h>
//Main function
int main()
{
int days = 0, totaldays, flight_num, dailyflights;
double distance, cur_distance = 0, totaldistance = 0, average_dist;
printf("How many days has your dragon been practicing?\n");
scanf("%d", &totaldays);
for(days=1; days <= totaldays; days++) {
printf("How many flights were completed in day #%d?\n", days);
scanf("%d", &dailyflights);
for (flight_num=1; flight_num <= dailyflights; flight_num++) {
printf("How long was flight #%d?\n", flight_num);
scanf("%ld", &distance);
totaldistance = distance + totaldistance;
}
printf(" total distance = %lf , dailyflights = %d\n", totaldistance, dailyflights); /*I printed this line to determine what isn't correct and I determined that totaldistance is not calculating correctly*/
average_dist = totaldistance / (float) dailyflights;
printf("Day #%d: The average distance is %.3f.\n", days, average_dist);
}
return 0;
}
最佳答案
你必须使用 %lf
而不是 %ld
来读取 double
的值到 distance
扫描
。
您应该使用 %f
而不是 %lf
来使用 printf 打印
因为 double
的值float
值是自动扩展的,所以不需要区分它们。
此外,在内循环之前,您需要设置 totaldistance = 0.0;
,这样您就可以将每天的航类与其他每天的航类分开累积,从而使平均距离计算正确。
关于c - 平均值不在嵌套for循环中计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804216/