简体   繁体   English

在 C++ 中使用 cout 打印浮点和双精度值

[英]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?为什么这个代码 output 是 10000.5 而不是 10000.50,有人能解释一下这背后的逻辑吗?

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). double (和一般的浮点变量)不存储数字的特定拼写(base-10 或其他)。 That would be way too inefficient, and the ability to store meaningless zeroes would waste memory.那效率太低了,存储无意义的零的能力会浪费 memory。

Instead, the numbers are encoded in a certain binary format .相反,数字以某种二进制格式编码。 Printing them reproduces the base-10 spelling from binary.打印它们会从二进制复制 base-10 拼写。

By default, C++ does not display trailing zeros, however the standard library <iomanip> can be used along with std::fixed from <iostream> .默认情况下,C++ 不显示尾随零,但是标准库<iomanip>可以与来自<iostream>的 std::fixed 一起使用。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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