abc*_*def 11 c++ format scientific-notation
是否可以通过以下方式格式化科学记数法中的字符串:
在mantisa中设置固定小数位:0
double number = 123456.789
Run Code Online (Sandbox Code Playgroud)所以这个数字应该合成
1e+5
Run Code Online (Sandbox Code Playgroud)
我无法为mantisa设置0小数点:
cout.precision(0);
cout << scientific << number;
Run Code Online (Sandbox Code Playgroud)
结果:
1.234568e+005
Run Code Online (Sandbox Code Playgroud)
您可以使用 C++20 来做到这一点std::format:
double number = 123456.789;
auto s = std::format("{:.0e}\n", number); // s == "1e+05"
s.erase(s.size() - 2, 1); // s == "1e+5"
Run Code Online (Sandbox Code Playgroud)
在std::format广泛使用之前,您可以使用{fmt} 库,std::format它基于:
#include <fmt/core.h>
double number = 123456.789;
auto s = fmt::format("{:.0e}\n", number); // s == "1e+05"
s.erase(s.size() - 2, 1); // s == "1e+5"
Run Code Online (Sandbox Code Playgroud)
免责声明:我是 {fmt} 和 C++20 的作者std::format。
我不知道如何在指数字段中获得一个数字,但以下内容符合您的所有其他要求。
#include <iostream>
#include <iomanip>
int main()
{
const double number = 123456.789;
std::cout << std::setprecision(0) << std::scientific << number << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1e+05
编辑:
通过标准(N3291)进行了快速搜索,在使用科学记数法时找不到任何关于指数字段中位数的内容。这可能是实现定义的。
我不确定你使用的是什么 C++ 编译器,它为你提供了 3 位数字的指数 \xe2\x80\x94C 和 C++ 标准要求至少 2 位数字,这就是g++ 确实如此。使用标准 C 或 C++ I/O 函数无法仅获取一位数字,因此您必须推出自己的解决方案。由于进行浮点到字符串的转换是一个非常棘手的问题[PDF],因此我强烈建议不要这样做,而是对结果进行后处理。
\n\n这是一种方法:
\n\n// C version; you can rewrite this to use std::string in C++ if you want\nvoid my_print_scientific(char *dest, size_t size, double value)\n{\n // First print out using scientific notation with 0 mantissa digits\n snprintf(dest, size, "%.0e", value);\n\n // Find the exponent and skip the "e" and the sign\n char *exponent = strchr(dest, \'e\') + 2;\n\n // If we have an exponent starting with 0, drop it\n if(exponent != NULL && exponent[0] == \'0\')\n {\n exponent[0] = exponent[1];\n exponent[1] = \'\\0\';\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n