C++ 打印浮点数

问题描述 投票:0回答:4

是否有打印浮点数的最佳方法(我正在使用长双精度数)?我尝试了几种方法,但似乎没有一种方法适用于所有类型的数字。

让我举例说明。

我有三份打印报表。

print(M_PI); // from cmath
print(1.234);
print(1.234e-10);

这些是 print(const long double &n) 的一些实现的结果:

简单计算

cout << n << endl;

3.14159 // not good
1.234 // good
1.234e-10 // good

精确计算

cout.precision(numeric_limits<long double>::digits10);
cout << n << endl;

3.14159265358979312 // good
1.23399999999999999 // bad
1.23400000000000008e-10 // not good

固定精度的 COUT

cout.precision(numeric_limits<long double>::digits10);
cout << fixed << n << endl;

3.141592653589793116 // good
1.233999999999999986 // bad
0.000000000123400000 // not good

还有其他一些“科学”而不是固定的可能性,但这显然是不可取的。

c++ floating-point cout
4个回答
1
投票

问题是一些十进制数无法用二进制精确表示。正如

1.0 / 3.0
没有精确的十进制表示一样,
1.0 / 10.0
(也称为
0.1
)也没有精确的二进制表示。

因此对于计算机来说,十进制中没有“自然表示”或“尽可能多的可用数字”的明确概念。

当您在代码中输入

0.1
时,它实际上会由内存中最接近的二进制值表示。将此二进制值转换回十进制(这总是可能的)会产生
0.1000000000000000055511151231257827021181583404541015625


1
投票

您可以使用 printf 或 sprintf ,如下所示:

float p1 = 1.234;
float p2 = 1.234e-10;
float p3 = M_PI;

printf("%.5g - %.5g - %.5g", p1, p2, p3);

输出:

1,234 - 1,234e-10 - 3,1416

0
投票

C++20 提供

std::format
,为您提供最短的十进制表示形式,并具有往返保证和正确的舍入:

#include <format>
#include <cmath>
#include <iostream>

int main() { 
  std::cout << std::format("{}\n", M_PI);
  std::cout << std::format("{}\n", 1.234);
  std::cout << std::format("{}\n", 1.234e-10);
}

输出:

3.141592653589793
1.234
1.234e-10

如果

std::format
在您的标准库实现中尚不可用,您可以使用它所基于的 {fmt} 库

免责声明:我是 {fmt} 和 C++20 的作者

std::format


-1
投票

实现一个接受流的方法,按照您喜欢的方式更改它并输出它

ios_base& myway (ios_base& str){

}
© www.soinside.com 2019 - 2024. All rights reserved.