Average of 3 numbers - displaying 2 decimals

I don't know how to display decimals. At the moment, the program shows integers. I need it to display numbers like 9.33 too.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
#include <iomanip>
#include <stdio.h>

using namespace std;

int main()
{
    int x, y, z;
    int M;
    cin>>x>>y>>z;
    M=(x+y+z)/3;
    cout<<M;
    return 0;
}
Last edited on
I tried to already, but I can't figure out how should i use it. This is what I've tried so far.
1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>
#include <stdio.h>

using namespace std;

int main()
{
    int x, y, z;
    double M;
    cin>>x>>y>>z;
    M=(x+y+z)/3;
    cout << setprecision(3) << M;
    cout << fixed;
    cout << setprecision(3) << M;
    return 0;
}

2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>
#include <stdio.h>

using namespace std;

int main()
{
    int x, y, z;
    double M;
    cin>>x>>y>>z;
    M=(x+y+z)/3;
    cout << setprecision(3) << M;
    cout << fixed;
    cout << setprecision(3) << M;
    return 0;
}
On line 12 is where the error is. You are doing integer math which will return an integer value:
(double) = ( (int) + (int) + (int) ) / (int);

Try casting the ints to doubles like so:
M = ( static_cast<double>(x) + static_cast<double>(y) + static_cast<double>(z) ) / 3.0;
This (x+y+z)/3; is doing integer division, the result is an integer. Though you can assign the result to a variable of type double, that doesn't change the result

Instead, make sure at least one of the operands (in this case 3.0) is type double, in order to do floating-point division.
 
    double M = (x+y+z)/3.0;


Edit: the suggestion by edge6768 is correct, but in my opinion, rather more complex than is needed here.
Last edited on
You can change it to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>
#include <stdio.h>

using namespace std;

int main()
{
	int x, y, z;
	double M;

	cout << fixed << setprecision(2);

	cin >> x >> y >> z;
	M = (double (x) + double(y) + double(z)) / 3;
	cout << M << endl;
	return 0;
}


The easiest way would be to just make x,y,z also double and then just use setprecision.
Topic archived. No new replies allowed.