【发布时间】:2014-03-06 15:50:24
【问题描述】:
所以我计算了从文件中读取的双精度值的平均值和标准偏差。
我的文件数据每行有1个数字:我的文件中的数据如下
1
2
3
4
5
6
7
8
9
10
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
FILE *inputfile= fopen("file.dat.txt", "r");
if (inputfile == NULL)
{
printf("Failed to open text file.\n");
exit(1);
}
double i;
double j=1;
double average;
double stdish=0;
double stdreal=0;
double x=0;
double sum=0;
double stdfinal;
while(fscanf(inputfile, "%lf", &i) != EOF){
x=x+1;
sum = sum + i;
j = i*i;
stdreal +=j;
}
average = sum/x;
stdish = (stdreal/x)-(average*average);
stdfinal = sqrt(stdish);
printf("The average is %.4lf\n", average);
printf("The standard deviation is %.4lf\n", stdfinal);
fclose(inputfile);
return 0;
}
我正在通过终端运行它。 我的数据文件是file.dat.txt。我想要做的是让用户通过终端输入文本文件,而不是在程序中。
像这样:./sdev < file.dat
我不确定如何在我的程序中实现它...
谢谢!
【问题讨论】:
-
你从
stdin而不是inputfile阅读。