这是我的代码:
/*
* This program computes simple statistics from a file of ASCII numbers
*/
/*
* File: statsMain.c
* Author: William Vu T Nguyen
* ID: C0436847
* Created on February 6, 2017, 12:10 PM
*/
#include "statistics.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void printStats(FILE *dest, const int count, const double mean,
const double ssdev);
// main program
int main(int argc, char** argv) {
FILE *pFile;
int count;
int x;
char buff[100] = {0};
char *pBuff = buff;
double numVal;
double sum;
double sumsq;
double calculatedMean;
double calculatedStdDev;
if (argc != 2) {
fprintf(stderr, "usage: %s dataFileName\n", argv[0]);
exit(EXIT_FAILURE);
} else {
if ((pFile = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Unable to open input file \"%s\"\n", argv[1]);
exit(EXIT_FAILURE);
} else {
while ((x = fgetc(pFile)) != EOF) {
*pBuff = x;
sscanf(pBuff, "%lf", &numVal);
sum += numVal;
sumsq += (sum * sum);
count++;
pBuff++;
}
calculatedMean = mean(sum, count);
calculatedStdDev = ssdev(sum, sumsq, count);
printStats(pFile, count, calculatedMean, calculatedStdDev);
}
fclose(pFile);
}
return (EXIT_SUCCESS);
}
void printStats(FILE *dest, const int count, const double mean,
const double ssdev) {
char str[100] = {0};
sprintf(str, "%d Values, Mean = %lf, Sample Standard Deviation = %lf"
, count, mean, ssdev); //deal with buffer
puts(str);
fprintf(dest, "%s", str);
}
如果我的代码显示我是C的新手那么请耐心等待,因为我还在学习阶段。我喜欢编程,电路设计和微控制器。在学习这些科目的时候,在学校里做得很可怕,但我从来没有让它成为我生活中的决心因素。感谢。
答案 0 :(得分:2)
你也是:
pFile
,它以只读方式打开,并尝试写入sum
,sumsq
和count
而不初始化sumsq += (sum * sum);
最好利用固有的stdin
和stdout
文件指针,然后你可以做类似的事情:
stats < input_file > output_file
stats
是您的计划。如果您使用的是Linux,则可以将程序链接到tee
并完成您正在尝试的操作(即输出到控制台和文件),但不需要额外的代码。
我将如何写它:
#include <stdlib.h>
#include <stdio.h>
#include "statistics.h"
void printStats(const int count, const double mean, const double ssdev);
int main() {
int count = 0;
double numVal, sum = 0.0, sumsq = 0.0;
double calculatedMean, calculatedStdDev;
while (scanf("%lf", &numVal)) {
sum += numVal;
sumsq += numVal * numVal;
count++;
}
calculatedMean = mean(sum, count);
calculatedStdDev = ssdev(sum, sumsq, count);
printStats(count, calculatedMean, calculatedStdDev);
return EXIT_SUCCESS;
}
void printStats(const int count, const double mean, const double ssdev) {
printf("%d Values, Mean = %lf, Sample Standard Deviation = %lf\n",
count, mean, ssdev);
}