Truncalicious

Hey, I can't seem to remember how to keep this from getting truncated. If I input 5 and 2, it comes out 2.00. Anyone have a solution?

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

int main(){
	int a, b;
	double avg;
	
	cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(2);
	
	cin >> a >> b;
	avg = a/b;
	cout << avg;
	return 0;
}
The division operation in line 13 is an integer division and therefore subject to truncation. You would have to do an explicit cast of either operand to double to force floating point arithmetic.
If I do avg = static_cast<double>(a/b); it still gives me the same problem. Any other way you'd do it?
I said ONE of the operands of the division. That is not what I said. What you show there is the cast of the result of the division, AFTER the operands have played their part. Do the cast only on one of the operands; either 'a' or 'b'. For sure on 'a' works.
Just doing avg = (double)a/b; should do it. I'm not sure which part of the equation is casted, but who cares.
Topic archived. No new replies allowed.