Home > Backend Development > C++ > How to Display Trailing Zeros Using std::cout.precision() in C ?

How to Display Trailing Zeros Using std::cout.precision() in C ?

DDD
Release: 2024-11-09 04:41:02
Original
970 people have browsed it

How to Display Trailing Zeros Using std::cout.precision() in C  ?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template