[英]Scanning in numbers from a text file and finding the sum,largest number, and product
我希望能够扫描来自名为numbers.txt的文本文件中的一行数字,然后在名为statistics.txt的文本文件中打印总和,最大数和乘积。
Numbers.txt中的数字如下所示:
1 2 3 4 5 6 7 8 9
目前,我已经找到一种在文本文件中分别查找数字总和和最大数量的方法,因为您已经注意到我有2个while循环,这是不正确的。 但是,我不知道如何在没有2个单独的while循环的情况下找到总和和最大数。我也不知道如何找出这些数字的乘积。
注意:2个while循环分别工作,如果我取出其中一个,则其他1个工作
#include<stdio.h>
int main()
{
int a, sum = 0, numbers, m;
FILE *filein, *fileout;
filein= fopen("numbers.txt", "r");
fileout = fopen("statistics.txt", "w");
//the sum part
while(fscanf(filein, "%d", &a) == 1)
{
sum += a;
}
fprintf(fileout, "Sum = %d \n", sum);
//the max part
while(fscanf(filein, "%d", &numbers) > 0)
{
if(numbers > m)
m = numbers;
}
fprintf(fileout,"Largest = %d\n", m);
fclose(filein);
return 0;
}
一个while
循环可以while
执行多个计算。 例如,您可以将两个循环合并为一个循环
while(fscanf(filein, "%d", &a) == 1)
{
sum += a; // update the sum
if ( a > m ) // update the max
m = a;
}
另请注意,您需要将m
初始化为INT_MIN。
要计算乘积,请从值1
并以*=
更新,类似于您对总和所做的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.