我的文件有一系列数字: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)为什么???
答案 0 :(得分:6)
您将double
变量的地址传递给scanf()
格式,该格式已被告知期望float
的地址。
while (fscanf(file, "%f", &num) > 0)
应该是:
while (fscanf(file, "%lf", &num) > 0)
答案 1 :(得分: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);
}
答案 2 :(得分:0)
如果你的C编译器 NOT 支持“%lf”,那么:
float num;
double dnum;
// etc.
scanf("%f", &num);
//etc.
dnum = (double) num; // use dnum in calculations