c++科学记数法,改变指数的位数

c++ scientific notation, change the digits of exponent

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

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

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

好像@Bob__ 说 visual studio 曾经有一个函数叫做:_set_output_format 它允许你改变指数 BUT 我相信这在 Visual Studio 2015 版本中被删除了。

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

The %e and %E format specifiers format a floating point number as a decimal mantissa and exponent. The %g and %G format specifiers also format numbers in this form in some cases. In previous versions, the CRT would always generate strings with three-digit exponents. For example, printf("%e\n", 1.0)would print 1.000000e+000. This was incorrect: C requires that if the exponent is representable using only one or two digits, then only two digits are to be printed.

In Visual Studio 2005 a global conformance switch was added: _set_output_format. A program could call this function with the argument _TWO_DIGIT_EXPONENT, to enable conforming exponent printing. The default behavior has been changed to the standards-conforming exponent printing mode.

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

#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() 将 return 您尝试打印的双精度字符串,您可以修改它以便为指数添加额外的数字。