gpt4 book ai didi

c++ - C++ 中 `double` 的 Java 样式打印

转载 作者:太空狗 更新时间:2023-10-29 20:50:29 25 4
gpt4 key购买 nike

在 C++ 中打印 double 时,是否有任何流操纵器组合(或标准 C++ 中的任何其他方法)可以让我获得“正确”的数字位数?

我所说的“正确”数字是指定义的位数 here :

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

在一个稍微简单的示例中,假设我们有三个 double 值:DD、D0 和 D1。 DD是“中间”,D1的尾数大1,D0的尾数小1。

当打印到某个非常大的任意精度时,它们会产生以下值(示例中的数字完全不正确):

D0 => 1.299999999701323987
DD => 1.300000000124034353
D1 => 1.300000000524034353

(EPSILON,指数为 0 时尾数的最低有效位的值为 ~ 0.0000000004)

在那种情况下,上面的方法会产生

D0 => 1.2999999997
DD => 1.3
DD => 1.3000000005

最佳答案

如果我没理解错的话,你想要std::to_chars .

value is converted to a string as if by std::printf in the default ("C") locale. The conversion specifier is f or e (resolving in favor of f in case of a tie), chosen according to the requirement for a shortest representation: the string representation consists of the smallest number of characters such that there is at least one digit before the radix point (if present) and parsing the representation using the corresponding std::from_chars function recovers value exactly. If there are several such representations, one with the smallest difference to value is chosen, resolving any remaining ties using rounding according to std::round_to_nearest.

这是一个低级函数,所以打印结果需要一些工作:

run on gcc.godbolt.org

#include <charconv>
#include <iostream>

int main()
{
double val = 0.1234;

char buf[64];
*std::to_chars(buf, buf + sizeof buf, val).ptr = '\0';

std::cout << buf << '\n';
}

此函数需要最新的标准库:GCC (libstdc++) 11 或更新版本,或 Clang (libc++) 14 或更新版本(当前为 trunk)。 MSVC 也支持它。

关于c++ - C++ 中 `double` 的 Java 样式打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54370268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com