c - 关于 C 语言文件 IO.如何通过文件输入计算平均值(fgets)
问题描述
任务是假设一个文件已经存在,该文件是每行一个分数,我们不知道文件中有多少分数。我们需要它来计算每个分数的平均值。一个例子:
test.txt=21
43
32
54
在测试文件中。我们需要它(21+43+32+54)/4
;我的进步是使用for循环输入分数值。接下来是输入值fgets()
。
但我的代码平均值不是动作。我认为我的代码错误是's'infgets
表示字符串。这样对吗?然后我的输入是字符串,但计算是双倍的。
而且我不知道在哪里更改我的代码。如果您有任何有用的意见,请告诉我。
解决方案
在您的代码中看到您使用 sum 作为整数和 one 作为数组并使用代码
sum = sum + one;
这是错误的,因为您无法将整个数组一次添加为一个值,就像您使用的那样。因此,您可以使用浮点变量并将文件的值扫描到它(使用 fscanf)并将其添加到总和并在每次扫描新行时更新它,而不是不必要和错误地使用数组。
我们在这里使用 feof() 遍历文件,它用于查找文件的结尾。
#include <stdio.h>
int main()
{
float sum=0,count=0,avg,val; // declaring necessary variables
FILE *fin;
if ( (fin = fopen("c:₩₩Ubuntu20.04₩₩scores.txt","r"))== NULL )// file is opened
printf ("file can't be opened");
else
{
while(!feof(fin)) // using while loop till the end of file
{
fscanf(fin,"%d",&val);
sum += val; // Math for sum here
count++;
}
}
fclose(fin);
avg = sum/count; // math for average calculation
printf("\n the average is : %.3f\n",avg"); // printing average till 3 decimal points
return 0;
}
上面的代码适用于任何长度的文件。PS如果你想提高英语https://play.google.com/store/apps/details?id=com.duolingo&hl=en_IN&gl=US 使用这个应用程序会有很大帮助
推荐阅读
- r - 将相同的值分散到多个列中
- .net - 如何解决 enitiy framwork 的错误包括
- scala - 使用作为类对象的属性实现 scala 特征
- java - checkmarx - 如何解决存储的绝对路径遍历问题?
- biztalk - BizTalk 消息上下文属性“MessageTracking.AdapterReceiveCompleteTime”
- visual-studio - 使用共享点位置作为公共存储库来存储 Visual Studio 项目,如 TFS/Azure DevOps
- python - 从特定列值中删除 *
- c# - NuGet API Wrapper - ProblemDetails 类处理
- aws-lambda - AWS Lambda 冷出会导致 API Gateway 超时(30 秒)吗?
- reactjs - 基于通配符路由的esri-arcgis请求拦截