Finding the Average of Four Numbers

I'm having a problem with making this code work. I need it to find the average of four numbers that the user will submit. The code looks like it should work, but I'm getting really weird output when it runs. Anyone see something wrong with it? Any help would be appreciated. Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;

int main()
{
	//Prompt the user to enter four numbers
	double number1, number2, number3, number4;
	cout << "Enter four numbers: ";
	cin >> number1, number2, number3, number4;
	
	//Compute average
	double average = (number1 + number2 + number3 + number4) / 4;
	
	//Display result
	cout << "The average of " << number1 << ", " << number2
	     << ", " << number3 << "and " << number4 << "is" << average
	     << endl;
	     
	return 0;
}
cin >> number1 >> number2 >> number3 >> number4;
@MiiNiPaa

Tried your suggestion, but the output is still inaccurate. Thanks for your help!
Can you post example of input and innacurate output.
1
2
3
4
5
	cin >> number1 >> number2 >> number3 >> number4;
	
	// Compute average, avoid integer division
	// double average = (number1 + number2 + number3 + number4) / 4;
        const double average = (number1 + number2 + number3 + number4) / 4.0 ;
Err, numberN is already double, integer division is not the problem here.
But using double constant explicitly is a good way to avoid problems if your program changes.
> Err, numberN is already double, integer division is not the problem here.

Yes. Thanks.
Since OP hasn't made it clear what is going wrong with his code, here is a suggestion
for calculating average:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <algorithm>
#include <initializer_list>

double average(const std::initializer_list<double> &list) {
    
    double sum = std::accumulate(list.begin(), list.end(), 0.0);
    return sum / list.size();
}

int main()
{
    double number1, number2, number3, number4;
    std::cout << "Enter four numbers: ";
    std::cin >> number1 >> number2 >> number3 >> number4;
    
    //Display result
    std::cout << "The average of " << number1 << ", " << number2
	      << ", " << number3 << " and " << number4 << " is: "
              << average({number1, number2, number3, number4})
	      << std::endl;
    
    return 0;
}


http://coliru.stacked-crooked.com/a/8ab97cb7df739db5
Last edited on
Thanks for all the help everyone. @MiiNiPaa- Tried your suggestion again, and it worked like it was supposed to. I'm not sure what the problem was before. Thank you! Thanks again for the extra suggestions everyone..
Topic archived. No new replies allowed.