Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

How to add a Average of the numbers in c++ text.stream

How to code Average of the numbers in case 5? I already done a convert string to int. How can I make average of the numbers from text file named "dane.txt"?

case 5: //srednia
                {
                    fstream plik;
                    plik.open("dane.txt");
                    while(!plik.eof())
                    {
                        plik>>a;
                        licznik++;
                        if((licznik)%3 == 0)
                        {
                            string str = a;
                            int m = atoi(str.c_str());
                            
                        }
                    }
                    plik.close();
                    break;
                }
question from:https://stackoverflow.com/questions/65914999/how-to-add-a-average-of-the-numbers-in-c-text-stream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add two variables to keep track of the count of numbers, and the total from adding up all the numbers (apologies for the English names).

Then at the end of the loop you can divide the total by the count and that is your average.

                int total = 0;
                int count = 0;
                ...
                while(...)
                {
                        ...
                        string str = a;
                        total += atoi(str.c_str());
                        ++count;
                }
                cout << "average is " << (double)total/count << '
';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...