Imprecise Averages

Jun 5, 2020 at 6:51pm
I'm trying to get the code here to be more precise, down to at least the second decimal but I don't know-how.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <iomanip>

int main()
{
    //Curly braces prevent "Garbage" Integers," These cause no real anwer to ever be stated
    int numOfData{};
    int sum{};
    int average{};
    double num[100]{};
    int i = 0;
  
    std::cout << std::fixed << std::setprecision(6);

        //Prints Message
    std::cout << "\n How many numbers would you like ? max 100 : ";
    std::cin >> numOfData;

    while (numOfData > 100 || numOfData <= 0)
    {
        std::cout << "\n        Error! number should in range of (1 to 100).";
        std::cout << "\n Enter the number again:";
        std::cin >> numOfData;
    }
    //Loop executed until 'i' is filled
    for (i = 0; i < numOfData; i++)
    {
        std::cout << ". Enter number " << i + 1 << ": ";
        std::cin >> num[i];
        sum += num[i];
    }

    //average = sum / numOfData;
    average = static_cast<double>(sum) / static_cast<double>(numOfData);

    std::cout << "\n The average is: " << average;

    return 0;
}
Last edited on Jun 5, 2020 at 6:52pm
Jun 5, 2020 at 7:30pm
this may be a sledgehammer for your fly.
https://en.wikipedia.org/wiki/Kahan_summation_algorithm

if this is too much to muddle thru, if I recall you can sort the input and sum in either direction and its 'pretty good'.

you could also just make average a double, so you can get decimal places. you set it to int...
:P (this is the real answer. the above 2 are just some things that you may find interesting, but probably don't want to code up at this point in your studies).
Last edited on Jun 5, 2020 at 7:34pm
Jun 6, 2020 at 1:42pm
You're entering doubles but storing sum as an int. Change line 8 to double sum{}

You don't need the num array. After all, once you add a number to sum, you never use it again.
Topic archived. No new replies allowed.