finding average of three numbers

we have been asked this question
" Write a program in C++ display the sum of 3 numbers. The code should also calculate and display the average of the 3 numbers. The output should be displayed as follows:
The sum of the 3 numbers entered:
The average of the 3 numbers entered:"

AND this i what i have tried so far but i could not get way of getting average displayed,instead the answer of sum is repeated to average.
#include <iostream>

using namespace std;

int main()
{
int a, b ,c,sum;
float average;
cin>>a>>b>>c;
sum = a+b+c;
cout<<"The sum of 3 numbers is:"<<sum<<endl;
average =sum/3;
cout<<"The average of 3 numbers is:"<<sum<<endl;
return 0;
}

SO WHAT TO DO? so as to get average get displayed?
cout<<"The average of 3 numbers is:"<<sum<<endl;

If you ask the program to show you the content of the variable "sum", that's what it will display.
Maybe you want the content of another variable to be shown...

tren bien
i got the answer!!!
solution
#include <iostream>

using namespace std;

int main()
{
int a, b ,c,sum;
float average;
cin>>a>>b>>c;
sum = a+b+c;
cout<<"The sum of 3 numbers is:"<<sum<<endl;
average =sum/3;
cout<<"The average of 3 numbers is:"<<average<<endl;
return 0;
}
It could be improved.

Example:
2 2 4
The sum of 3 numbers is:8
The average of 3 numbers is:2


The average is always an integer, though it was declared as type float. You need to make at least one of the values a floating-point type in order to do floating-point divide.

Hence:
 
    average = sum/3.0;

Here 3.0 is type double, so a floating-point division will be done, giving a result of type double.

One small comment, rather than declaring all the variables at the start, it is usually better to not declare a variable until you have an actual value to assign to it.
1
2
3
4
5
6
7
    cout << "Please enter three integers:\n";
    int a, b ,c;
    cin >> a >> b >> c;
    int sum = a+b+c;
    cout << "The sum of 3 numbers is:     " << sum << endl;
    double average = sum/3.0;
    cout << "The average of 3 numbers is: " << average << endl;
thanks a lot for your comment
Topic archived. No new replies allowed.