【问题标题】:c++ scientific notation, change the digits of exponentc++科学记数法,改变指数的位数
【发布时间】:2020-06-14 18:31:23
【问题描述】:

我正在使用此代码将科学计数法数字输出到文件:

file << scientific << setprecision(10) << num << endl;

例如,如果数字是 3.0,我从代码中得到 3.0000000000E+00。如何将指数部分的数字设为 3 位?我想得到 3.0000000000E+000。

【问题讨论】:

标签: c++ scientific-notation


【解决方案1】:

就像@Bob__ 所说的那样,Visual Studio 曾经有一个名为:_set_output_format 的函数,它允许您更改指数,我相信这已在 Visual Studio 2015 版本中被删除。

引用于Portable printing of exponent of a double to C++ iostreams

%e%E 格式说明符将浮点数格式化为 十进制尾数和指数。 %g%G 格式说明符也 在某些情况下以这种形式格式化数字。在以前的版本中, CRT 将始终生成具有三位指数的字符串。为了 例如,printf("%e\n", 1.0) 将打印 1.000000e+000这是 不正确:C 要求如果指数仅可使用 一位或两位数,则只打印两位数。

在 Visual Studio 2005 中添加了一个全局一致性开关: _set_output_format。程序可以使用参数_TWO_DIGIT_EXPONENT 调用此函数,以启用符合要求的指数打印。 默认行为已更改为符合标准的 指数打印模式。

因此,如果您真的想用 3 位指数编写,为了解决您的问题,需要修改输出。您可以通过将双精度转换为字符串来实现,例如:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>


std::string getStrCpy(double dbl) {
    std::ostringstream str;
    str << std::scientific << std::setprecision(10) << dbl;
    std::string s = str.str();
    std::cout << s; // Prints 3.0000000000e+00
    return s;
}

int main() {

    double d = 3.0;
    std::cout.precision(10);
    std::cout << std::scientific;

    std::cout << d << '\n'; // Prints 3.0000000000e+00
    getStrCpy(d); // Will also print 3.0000000000e+00

    return 0;
}

现在getStrCpy() 将返回您尝试打印的双精度字符串,您可以对其进行修改,以便为您的指数添加一个额外的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多