平均值不在嵌套for循环中计算

时间:2015-09-27 03:16:05

标签: c loops for-loop average

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

1 个答案:

答案 0 :(得分:2)

您必须使用%lf代替%ld,才能使用doubledistance的值读取到scanf

由于%f值会自动展开,因此您应%lf代替double 打印 printffloat的值并且没有必要区分它们。

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