Maurice Abney
Maurice Abney

Reputation: 223

Why am I not getting correct value when attempting to find the average value of n elements?

I'm going through an O'reilly programming book, and one of the questions is to "write a program to average n elements".

This is the code that I have:

#include <iostream>

int n; //number of numbers
int number; //the numbers to be averaged
float avg; //the average of the elements
int counter; //iterator

int main()
{
    std::cout << "Please enter the number of elements you want averaged: ";
    std::cin >> n;
    avg = 0;

    counter = 0;
    while (counter < n)
    {
        std::cout << "enter number: ";
        std:: cin >> number;

        number += number;

        ++counter;

    }

    avg = number/n;

    std::cout << "Average of your " << n << " elements is: " << avg;

    return 0;
}

For some reason, when I try to use 3 values of 3, i get a average of 2. I'm certain there's a problem with my declaration of "number" because it doesn't take the value of each number I enter and add it with each other. Could someone help me fix my mistake. I want my code to work for the general case; not just 3 elements. Thanks.

Upvotes: 1

Views: 94

Answers (3)

Patashu
Patashu

Reputation: 21773

Two problems.

1)

    std:: cin >> number;

    number += number;

I assume that number is meant to be the sum of all numbers, but here you are also using it to store a single number, and when you assign a value to a variable it overrides what was already there. You must use two different variable names, such as

    std:: cin >> number;

    sum += number;

2)

number/n; is integer division since number is integer and n is integer. Integer division rounds down. Having the result of the expression assigned to a float is not enough - it is too late, the expression was already computed as integer division.

You want float division, so do sum/(double)n for example.

Upvotes: 5

John3136
John3136

Reputation: 29265

You read the input into number, but you aren't actually keeping a total of all the numbers entered which is what you really need for this problem.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258588

You read the number 3. The you say number += number, which makes it 6, and increment counter to 1. Then you read number again, it becomes 3, add it again, again 6, increment, counter. The third time, the same happens.

So you get 6/2 which is 3.

Upvotes: 1

Related Questions