Home >Backend Development >C++ >Why Does `std::cout.precision()` Not Display Trailing Zeros for Floating-Point Numbers?

Why Does `std::cout.precision()` Not Display Trailing Zeros for Floating-Point Numbers?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 21:14:01574browse

Why Does  `std::cout.precision()` Not Display Trailing Zeros for Floating-Point Numbers?

std::cout.precision() and Trailing Zeros

Understanding the correct usage of std::cout.precision() is crucial when displaying floating-point numbers. In this article, we'll examine a specific example to resolve an unexpected behavior.

Initial Code and Issue

Consider the following code that attempts to display the result of dividing two integers as a floating-point number:

#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;
}

This code is expected to display 0.5000, but instead, it prints 0.5. This discrepancy arises due to the nature of the original data types being integers.

Resolution: std::fixed Manipulator

To display trailing zeros for floating-point numbers, you must pass the std::fixed manipulator to std::cout. This manipulator ensures that the decimal representation uses fixed-point notation, preserving trailing zeros.

#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;
}

With the std::fixed manipulator, the code now correctly prints 0.5000. The std::setprecision() manipulator remains responsible for specifying the desired number of decimal places.

The above is the detailed content of Why Does `std::cout.precision()` Not Display Trailing Zeros for Floating-Point Numbers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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