for循环运行的时间比指定的多吗?

时间:2016-02-26 00:09:36

标签: 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)

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

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