c - For 循环运行的时间比指定的时间长?

标签 c for-loop scanf

所以我的代码所做的是,它接受一个数字列表并输出所有数字的连续滚动平均值。我的 scanf 函数运行了额外的时间,所以我只是输入了一个零。我怎样才能解决这个问题?这是我所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    int i,n;
    double numbers[100]; double previous[100]; double x[100];
    double mean[100]; double old_average[100]; double new_average[100];
    printf("Total amount of numbers: ");
    scanf("%d\n", &n);
    for (i=1; i<n+1; i++){
        scanf("%lf\n", &numbers[i]);
        }
        old_average[1] = numbers[1] / 1;
    for (i=1; i<n+1; i++){
        new_average[i] = (((old_average[i] * (i)) + numbers[i+1]) / (i+1));
        old_average[i+1]=new_average[i];
        }
    printf("%lf\n", old_average[1]);
    for (i=1; i<n+1; i++){
        printf("%lf\n", new_average[i]);
    }


        //new_average[i] = (((old_average[i] * i-1) + numbers[i]) / i);
        //mean[j] = numbers[i] + mean

    //printf("%f\n", old_average[1]);
    //for (i=2; i<n+2; i++){
      //  printf("%f\n", new_average[i]);
    //}
    return 0;
}

这是输入和输出的样子

Input:  
Total amount of numbers: 10
10
8
9
15
12
2
3
8
7
11
0(this is the extra loop)
Output: 
10.0
9.0
9.0
10.5
10.8
9.3
8.4
8.4
8.2
8.5
-1.#QNAN0 (this is the extra loop)

如何解决这个问题?

最佳答案

在传递给 scanf() 的每个格式说明符中删除额外的 \n,这意味着“读取直到文件结尾或下一个非空白字符” .

关于c - For 循环运行的时间比指定的时间长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640928/

相关文章:

c - 在 C 中调用 exit() 后进程会发生什么样的清理?

c - 在 CUDA 中主机和设备之间传递变量

Python Pandas 在 For 循环中替换列中的字符串

具有结构的 C++ vector 不起作用?

c - 为什么 &p 和 &a[0] 不同?

java - 指向结构指针的指针作为 JNA 中的参数

php - 用 for 循环替换 while ($row=mysql_fetch_array($res)) 循环

javascript - 使用 for 和 if 语句隐藏/显示多个图像的迭代函数

c - 使用 scanf 读取空间

c - scanf用数组格式化多个特殊字符