如何从文件中取平均值,并使用c将结果放回新文件中



我正在编写一个程序,它将从名为numbers.txt的文件中获取10个数字,并将它们放入一个数组中,对它们取平均值,然后将平均值写回文件中。我已经创建并存储了名为numbers.txt的文件。当我运行我的代码,它不处理,我不知道为什么。我对编码非常陌生,学习缓慢。有人能检查一下这段代码并帮我弄清楚吗?

感谢下面是我的代码:

#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[]){
int i = 0, sum = 0, n = 0,avg = 0;
FILE *numbers.txt;
fin = fopen("numbers.txt", "r");
while(fscanf(numbers.txt, "%d", &n) != EOF){
sum += n;
i++;
avg = (sum / i);
}
printf("The average is %d.n", avg);
fclose(numbers.txt);
return 0;
}

numbers.txt作为第一个参数调用fscanf(close也是如此)。这是无效的,numbers.txt不是一个有效的符号名称。

你的open,分配给fin。将字符串中除fin外的所有地方替换为numbers.txt。变量名中不能有.。您所显示的代码甚至无法编译。


您还应该检查fscanf的结果,以查找EOF以外的内容。您知道何时到达了文件的末尾,但不知道是否成功地读入了一个值。如果输入成功,它应该是1。


根据您的文件结构,您可能希望在该格式字符串的前面添加空格字符,或者对其进行一些其他更改,根据fscanf的文档。

"…它不处理"不是很有用的描述,你得告诉我们你到底看到了什么。如果编译器报错,那么您需要在问题正文中包含编译器错误。如果代码编译了,但没有正确运行,你需要告诉我们你期望发生什么,以及实际发生了什么(例如,"我期望看到这个特定的输出,但我没有得到任何输出/我得到了垃圾/我得到了一个我不期望的值",等等)。

如果你发布的是你实际想要运行的,那么你很可能会在变量numbers.txt上得到编译器错误。.不是标识符1的有效字符,因此像FILE *numbers.txt这样的声明将被编译器拒绝。

我冒昧地修改了你的代码并做了注释——希望这对你有帮助:

/**
* While the compiler couldn't care less about how you format your code,
* it's a good idea to use indentation and whitespace to make your code
* easier for other people to read.  Exact styles and preferences vary,
* what matters is that you're consistent.  This is the style I prefer.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
int i = 0, sum = 0, n = 0,avg = 0;
/**
* numbers.txt is not a valid identifier - you can't use that as a variable
* name.  I'm going to assume you meant to use fin as that's the target of
* your fopen call.  Note that you can initialize the variable with the
* result of the function call.  
*/
FILE *fin = fopen("numbers.txt", "r");
/**
* It's always a good idea to make sure the fopen call succeeded before
* trying to use the file pointer.
*/
if ( !fin ) // or fin == NULL 
{
fputs( "Could not open numbers.txt", stderr );
exit( EXIT_FAILURE );
}
/**
* With the *scanf functions, it's better to check to see if you
* got the expected number of inputs rather than checking for EOF.
* It's possible for *scanf to return 0 if the first input character
* doesn't match the format specifier - e.g., if you read an 'a' or a 
* '.' or something like that.  
* 
* In this case we expect 1 integer to be read, so we check that fscanf
* returns 1.  If it doesn't, *then* we check for EOF or bad input.  We'll
* create a new variable named items_read to store the return value
* of fscanf.  
*
* For this example, we'll bail out immediately if we see bad input.  
* There are ways to recover from bad input, but they'll make this 
* example longer than it needs to be.
*/
int items_read;
while( (items_read = fscanf(fin, "%d", &n)) == 1)
{
sum += n;
i++;        
/**
* We do not need to compute the average in the body of the loop;
* that's something that only needs to be done after we've read
* all the inputs.
*/
}
/**
* Make sure we exited the loop normally by checking that items_read is
* not 0 and that we don't have a read error on the input stream:
*/
if ( items_read == 0 || ferror( fin ) )
{
fputs( "Badly formed input file or error on input - exiting", stderr );
fclose( fin );
exit( EXIT_FAILURE );
}
/**
* Otherwise we've read to the end of the file.  
*
* It's a good idea to free resources (file pointers, dynamically allocated
* memory, etc.) as soon as you're done with them, rather than waiting
* until the end of the program, so we'll close the input file here. 
*/
fclose(fin); 
/**
* *Now* we compute the average.
*/ 
avg = (sum / i);
printf("The average is %d.n", avg);

return EXIT_SUCCESS;
}

请记住,整数除法的结果是整数——1/2的结果是0而不是0.5。如果要计算浮点平均值,则需要将nsumavg声明为double2,并且需要使用%lf作为fscanf调用的转换说明符,使用%f作为printf调用的转换说明符:

double sum = 0.0, n = 0.0, avg = 0.0;
...
while( (items_read = fscanf( fin, "%lf", &n )) == 1 )
...
printf( "The average is %fn", avg );

  1. 标识符(变量名、函数名、枚举常量等)中唯一可以出现的标点符号是下划线——_
  2. 除非你真的受空间限制,或者你特别不想要那个级别的精度,使用double而不是float。大多数情况下,float值都会隐式提升为double

最新更新