Truncating

Hey, I can't seem to remember how to keep this from getting truncated. If I say avg = 4.5 it outputs properly. How do I get it to output 4.5 in this code instead of 4? Thanks!

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main(){
	double avg;
	avg = 9/2;
	cout << avg;
	return 0;
}
Try making sure the numbers being divided, are also doubles, or floats.
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main(){
	double avg;
	avg = 9.0/2.0;
	cout << avg;
	return 0;
}
whitenite1 tell you.
you use float or float instead int
but use to declare a variable
e.g
float a=8,b=3;
cout<<a/b;

OR
cout<< 8.0/3.0;
Thanks guys
Well actually, my original problem was more like this. If I input 5 and 2, for example, it outputs 2.00.

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 = static_cast<double>(a/b);
	cout << avg;
	return 0;
}
Last edited on
That's because you declared a and b as ints. They will always be whole numbers. Declare a and b as floats, and the program should work a LOT better.
I was asked for them to be ints
Topic archived. No new replies allowed.