【发布时间】:2016-07-19 00:37:49
【问题描述】:
这是我写的代码:
#include <stdio.h>
#include<stdlib.h>
int main(void)
{
float x;//the data value
float sum=0.0;//the running total of the values readd
int n=0;//the number of data values read
float cube;
FILE* fin = fopen("sumcubes.in", "r"); /* open for reading */
FILE* fout=fopen("sumcubes.c","w");
while(1){
fscanf(fin,"%f",&x);
if(feof(fin))break;
n++;
cube=x*x*x;
sum=sum+cube;
}
fprintf(fout,"There are %d values in the file:",n);
fprintf(fout,"The sum of cubes of these values is:%f",sum);
fclose(fin);
fclose(fout);
system("sumcubes.in");
system("sumcubes.c");
system("pause");
return 0;
}
我期待它会读取文件中的值,然后将每个值立方。在对文件中的每个值进行立方计算后,它将获得这些立方值的总和。但是没有任何内容打印到输出中。
【问题讨论】:
-
文件创建了吗?您应该检查 fopen() 的结果以验证它是否成功。
-
您能解释一下您希望如何通过
system()库调用执行两个文件,它们实际上不包含可执行程序,而是包含数字列表? -
使用调试器单步调试代码
-
假设
int main(void\n只是一个错字,请检查fin和fout的值,如果值是NULL,还要检查errno。我怀疑您需要确保输入文件位于正确的目录中。 -
顺便说一句,您可能希望在每个打印字符串的末尾添加 '\n'。并不是说这似乎与您的问题密切相关。