3

我有一个包含一系列数字的文件:9 1 2 1

我试图找出比率 subsum/sum

#include <stdio.h>
void main()
{ 
    double subSum = 0;
    double sum    = 13;
    double num    = 0;
    double x      = 0;
    FILE*  file   = fopen("text.txt", "r");

    while (fscanf(file, "%f", &num) > 0)
    {
        subSum = subSum + num;
        x      = subSum / sum;

        printf("%f",x);
        printf("\n");
    }

    fclose(file);
}

但它一直打印零(0.00000000000)为什么???

4

3 回答 3

6

您正在将double变量的地址传递给一种scanf()格式,该格式已被告知需要 a 的地址float

while (fscanf(file, "%f", &num) > 0)

应该:

while (fscanf(file, "%lf", &num) > 0)
于 2013-08-27T20:40:46.583 回答
0

如果您的 C 编译器支持 "%lf",则:

 float  num;
 double dnum;

 // etc.

 scanf("%f", &num);

 //etc.

 dnum = (double) num;  // use dnum in calculations
于 2013-08-27T20:45:14.400 回答
0
#include<stdio.h>
void main()
{ 
double subSum=0;
double sum=13;
int num=0;
double x=0;
FILE *file = fopen("text.txt", "r");
while(fscanf(file, "%d", &num) > 0){
    subSum=subSum+(double)num;
    x= subSum / sum;
    printf("%f",x);
    printf("\n");
 }
fclose(file);
}
于 2013-08-27T20:43:27.813 回答