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

标签 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;
}

最佳答案

你必须使用 %lf 而不是 %ld 来读取 double 的值到 distance 扫描

您应该使用 %f 而不是 %lf 来使用 printf 打印 double 的值 因为 float 值是自动扩展的,所以不需要区分它们。

此外,在内循环之前,您需要设置 totaldistance = 0.0;,这样您就可以将每天的航类与其他每天的航类分开累积,从而使平均距离计算正确。

关于c - 平均值不在嵌套for循环中计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804216/

相关文章:

c - linux内核中具有相同签名的函数

c - 让程序在 C 中重复输入

r - 计算数据帧的每一行与另一个数据帧中的所有其他行之间的欧几里得距离

batch-file - 在 'for' 循环中使用变量

c - C 中检查文件是否存在特定扩展名或模式的函数

c - 如何使用 gdb 进入 openGL API?

c++ - * 三角形图案设计问题

Python 从变量 (i,20) 开始迭代范围

python - 在 requests.get 中循环获取分页参数

c - 函数内的 pthread_exit()