簡體   English   中英

從文本文件中掃描數字並找到總和,最大數字和乘積

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM