简体   繁体   English

从文本文件中扫描数字并找到总和,最大数字和乘积

[英]Scanning in numbers from a text file and finding the sum,largest number, and product

I want to be able to scan in a line of numbers from a text file called numbers.txt and then print the sum, largest number, and product in a text file called statistics.txt. 我希望能够扫描来自名为numbers.txt的文本文件中的一行数字,然后在名为statistics.txt的文本文件中打印总和,最大数和乘积。

The numbers in numbers.txt would look like: Numbers.txt中的数字如下所示:

1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9

Currently, i have found a way to find the sum and largest number of the numbers in the text file separately, as you've noticed i have 2 while loops which is incorrect. 目前,我已经找到一种在文本文件中分别查找数字总和和最大数量的方法,因为您已经注意到我有2个while循环,这是不正确的。 However, i do not know how to find both the sum and largest number without 2 individual while loops.Also i do not know how to find out the product of the numbers at all. 但是,我不知道如何在没有2个单独的while循环的情况下找到总和和最大数。我也不知道如何找出这些数字的乘积。

Note: the 2 while loops work individually, if i take out either 1 of them, the other 1 works 注意: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;
}

A single while loop can perform multiple calculations at the same time. 一个while循环可以while执行多个计算。 For example, you can combine your two loops into one like this 例如,您可以将两个循环合并为一个循环

while(fscanf(filein, "%d", &a) == 1)
{
    sum += a;      // update the sum

    if ( a > m )   // update the max
       m = a;
}

Also note that you need to initialize m to INT_MIN. 另请注意,您需要将m初始化为INT_MIN。

To compute a product, start with a value of 1 and update with *= , similar to what you did for the sum. 要计算乘积,请从值1并以*=更新,类似于您对总和所做的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM