【问题标题】:Average not calculating in nested for loop在嵌套 for 循环中不计算平均值
【发布时间】:2015-09-27 03:16:04
【问题描述】:

我很困惑这个问题。我的总距离计算不正确。我不确定这是否是因为我错误地设置了循环,或者我做错了什么。我每次平均得到-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;
}

【问题讨论】:

  • 你需要在每个内部循环开始之前将totaldistance设置为零。

标签: c loops for-loop average


【解决方案1】:

您必须使用%lf 而不是%ld 来读取double 的值到distancescanf

您应该使用%f 而不是%lf打印 doubleprintf 的值,因为float 值会自动扩展,无需区分它们。

另外,在内循环之前,您需要设置totaldistance = 0.0;,以便将每天的航班与每天的航班分开累积,以正确计算平均距离。

【讨论】:

  • 这些都很好,但只是问题的一部分。代码还需要在内循环开始之前将totaldistance设置为0.0
  • 谢谢!这解决了所有整数的平均计算。我仍然收到十进制数字错误。该程序将 10+12.5+15 解释为 10+12+5+15 ,因此对于任何有带小数的航班的日子,我都会给出错误的平均值。编辑结合乔纳森将总距离设置为 0 的建议解决了问题
  • @JonathanLeffler 谢谢!这解决了我最后的问题。你能解释一下为什么需要将 totaldistance 重置为 0,因为我真的很难过。
  • @tonomon:当你不将totaldistance重置为零时,你将第二天的距离加到第一天的距离之和,然后除以第二天的航班数,当然,这是完全错误的计算。
猜你喜欢
  • 2016-12-22
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多