简体   繁体   中英

Printing float and double values using cout in C++

For the following code:

#include <iostream>
using namespace std;
class Hall
{
 public:
 double cost;
};
int main()
{
 Hall hall;
 hall.cost=10000.50;
 cout<<hall.cost;
 return 0;
}

Why does this code output 10000.5 and not 10000.50, can someone explain the logic behind this?

can someone explain the logic behind this?

The default behaviour is not show any trailing zeroes.

double (and floating-point variables in general) don't store a specific spelling of the number (base-10 or otherwise). That would be way too inefficient, and the ability to store meaningless zeroes would waste memory.

Instead, the numbers are encoded in a certain binary format . Printing them reproduces the base-10 spelling from binary.

By default, C++ does not display trailing zeros, however the standard library <iomanip> can be used along with std::fixed from <iostream> . Here is an example:

#include <iostream>
#include <iomanip>
int main() {
  double myVar = 123.4;
  std::cout << std::fixed << std::setprecision(2); // 2 trailing digits
  std::cout << myVar << std::endl;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM