繁体   English   中英

准确打印浮点数

[英]Printing floating-point numbers accurately

自 1990 年代以来,人们就知道如何快速准确地打印浮点数<\/a>。 Scheme 和 Java 编程语言已经实现了这个算法,但我在 C++ 中找不到类似的东西。

本质上,我正在寻找满足以下测试用例的一小段高效的代码:

void test(double dbl, const char *expected) {
    std::string actual = ...;
    assert(actual == expected);
}

test(3.0, "3.0");
test(3.1, "3.1");
test(0.1, "0.1");
test(1.0 / 3.0, "0.3333333333333333");   // Or maybe one more digit?

您的任务可以使用 C++17 中出现的std::to_chars函数来解决: https ://en.cppreference.com/w/cpp/utility/to_chars

示例解决方案:

#include <cassert>
#include <charconv>
#include <string>

void test(double dbl, const char *expected) {
    std::string actual;
    actual.resize(64);
    auto end = std::to_chars(actual.data(), actual.data() + actual.size(), dbl).ptr;
    actual.resize(end - actual.data());
    assert(actual == expected);
}

int main() {
    test(3.0, "3");
    test(3.1, "3.1");
    test(0.1, "0.1");
    test(1.0 / 3.0, "0.3333333333333333"); 
}

编译器资源管理器中的演示: https ://gcc.godbolt.org/z/G7zrTPKTh

暂无
暂无

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

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