Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of std::cout.precision() - not printing trailing zeros

I see many questions about the precision number for floating point numbers but specifically I want to know why this code

#include <iostream> #include <stdlib.h> int main() {   int a = 5;   int b = 10;   std::cout.precision(4);   std::cout << (float)a/(float)b << "\n";   return 0; } 

shows 0.5? I expect to see 0.5000. Is it because of the original integer data types?

like image 420
mahmood Avatar asked Jun 27 '13 11:06

mahmood


People also ask

How do you use precision in cout?

You can set the precision directly on std::cout and use the std::fixed format specifier. double d = 3.14159265358979; cout. precision(17); cout << "Pi: " << fixed << d << endl; You can #include <limits> to get the maximum precision of a float or double.

How do I print float values without trailing zeros?

print( '{:,g}'. format( X ) worked for me to output 3 where X = 6 / 2 and when X = 5 / 2 I got an output of 2.5 as expected. old question, but.. print("%s"%3.140) gives you what you want.

How do you show precision in C++?

By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.


1 Answers

#include <iostream> #include <stdlib.h> #include <iomanip> int main() {   int a = 5;   int b = 10;   std::cout << std::fixed;   std::cout << std::setprecision(4);   std::cout << (float)a/(float)b << "\n";   return 0; } 

You need to pass std::fixed manipulator to cout in order to show trailing zeroes.

like image 79
Nemanja Boric Avatar answered Oct 02 '22 19:10

Nemanja Boric