简体   繁体   中英

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.

The numbers in numbers.txt would look like:

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. 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.

Note: the 2 while loops work individually, if i take out either 1 of them, the other 1 works

#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. 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.

To compute a product, start with a value of 1 and update with *= , similar to what you did for the sum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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