Correct Use of std::cout.precision() to Display Trailing Zeros
In C , std::cout.precision() sets the precision for floating-point numbers. However, it does not automatically display trailing zeros. To resolve this issue, understanding the appropriate usage of std::cout.precision() is crucial.
In the given 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; }
The precision is set to 4, but the output is 0.5 instead of 0.5000. This is because the division operation results in a double-precision floating-point value, and std::cout default format does not include trailing zeros.
To display trailing zeros, the std::fixed manipulator must be passed to cout. This instructs cout to use a fixed-point notation, which explicitly displays trailing zeros. The corrected code:
#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; }
Now, the output will be 0.5000, as expected. std::setprecision() sets the precision to 4, and std::fixed ensures that trailing zeros are displayed.
The above is the detailed content of How to Display Trailing Zeros Using std::cout.precision() in C ?. For more information, please follow other related articles on the PHP Chinese website!