+ 1

How to output an integer as a float number?

In C++, if we initialize 2 float variables as 4.0 and 4.0 and find their sum (float variable), it output's 8 and not 8.0. Why so? N how to make the output 8.0?

2nd Apr 2017, 8:56 AM
Arsh
Arsh - avatar
3 odpowiedzi
+ 1
use setprecision(n) manipulator, where n is decimal precision. example float f =3.14159; cout <<setprecision(4) << f << '\n'; cout <<setprecision(9) << f << '\n'; Output: 3.1416 3.14159
2nd Apr 2017, 9:08 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 1
Use float(sum) instead of sum at the time when you want to print. cout << float(sum); This is explicit type conversion.
2nd Apr 2017, 9:49 AM
Mihir Patel
0
1+2+3+5÷4.0
3rd Apr 2017, 5:06 AM
Saurabh singh