Rol*_*lig 5 c++ floating-point
自 20 世纪 90 年代起,人们就知道如何快速准确地打印浮点数。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?
Run Code Online (Sandbox Code Playgroud)
双精度字面值会转换为浮点数,浮点数可能与字面值相同,也可能不同。然后,浮点数被转换回字符串。该字符串应尽可能短,同时表示十进制数,当解释为双精度文字时,将再次产生相同的浮点数。
如何使用 cout 以全精度打印双精度值?看起来相关,但接受的答案中的代码无法正确处理 3.1 情况。
您的任务可以使用std::to_charsC++17 中出现的函数来解决: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");
}
Run Code Online (Sandbox Code Playgroud)
编译器资源管理器中的演示:https://gcc.godbolt.org/z/G7zrTPKTh
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |