gpt4 book ai didi

c++ - 使用 C++ 打印带有一个前导零的指数符号

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:17 25 4
gpt4 key购买 nike

我正在生成一个文本文件用作 FORTRAN 输入文件。 FORTRAN 程序指定它读取的值必须采用这样的格式

1.0

必须打印为

0.1000000E+01

截至目前,我最接近使用 iostream 的是

1.000000E+00

代码

cout << setprecision(6) << fixed << scientific << uppercase;
_set_output_format(_TWO_DIGIT_EXPONENT);
cout << 1.0 << endl;

有谁知道如上所示获取前导零的最佳方法,最好使用 ostream 而不是 printf?

最佳答案

正如我所说,你的要求是不标准的,但你可以通过一个技巧来实现:

#include <iostream>
#include <iomanip>
#include <cmath>

class Double {
public:
Double(double x): value(x) {}
const double value;
};

std::ostream & operator<< (std::ostream & stream, const Double & x) {
// So that the log does not scream
if (x.value == 0.) {
stream << 0.0;
return stream;
}

int exponent = floor(log10(std::abs(x.value)));
double base = x.value / pow(10, exponent);

// Transform here
base /= 10;
exponent += 1;

stream << base << 'E' << exponent; // Change the format as needed

return stream;
}

int main() {
// Use it like this
std::cout << std::setprecision(6) << std::fixed;
std::cout << Double(-2.203e-15) << std::endl;
return 0;
}

Double需要包装器,因为您无法重新定义 <<对于 double .

我没有测试那种分离方式exponentbase反对 float ,也许你可以想出一个更好的选择,但你明白了:)

关于c++ - 使用 C++ 打印带有一个前导零的指数符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com