Finding the average

May 31, 2018 at 11:52am
For some reason I get 1.5 as a answer when it should be 2.5. I'm trying to find the number n for example 1234 number's sum average. 1 + 2 + 3 + 4 = 10 Average = 2.5

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
  #include <iostream>

using namespace std;

int main()

{
    int n, sk, kiek, sum;
    double vid;

    cout << "Iveskite skaiciu: \n";
    cin >> n;

    sum = 0;
    kiek = 0;

    while (n > 0) {

        n = n / 10;
        sk = n % 10;
        sum += sk;
        kiek++;




    }

    vid = (double) sum / kiek;
    cout << vid;


    return 0;
}
Last edited on May 31, 2018 at 11:53am
May 31, 2018 at 11:58am
Your code takes the number, and divides it by ten, and then you are looking at the last digit.

If you input 1234, when does your code add 4 to the sum? Never.
May 31, 2018 at 12:00pm
But sum = sum + sk than it adds. Doesn't it?
May 31, 2018 at 12:10pm
Never mind I found the problem. The % had to be first done and than / .
May 31, 2018 at 12:35pm
Just for the fun of it, using some more advanced C++ features:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <algorithm>

using std::string;
using std::cin;

int main()
{
  std::string input;
  cin >> input;
  auto lambda = [count = 0](double a, int b) mutable { return a + (b-'0'-a)/++count; };
  std::cout << "\n Ave = " << std::accumulate (input.begin(), input.end(), 0.0, lambda);
}


May 31, 2018 at 8:18pm
well if input is suddenly a string rather than an int, one need not make things so complex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s("1234");
    double sum=0, sz=s.size();
    for(auto& c : s)
        sum += c-'0';
    cout << sum/sz << endl;

    return 0;
}

2.5
Last edited on May 31, 2018 at 8:24pm
Topic archived. No new replies allowed.