使用C ++以1开头的零打印指数表示法 [英] Print exponential notation with one leading zero with C++

查看:63
本文介绍了使用C ++以1开头的零打印指数表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个文本文件,用作FORTRAN输入文件.FORTRAN程序指定其读取的值必须采用以下格式:

I am generating a text file to be used as a FORTRAN input file. The FORTRAN program specifies that the values it reads must be in a format such that

1.0

必须打印为

0.1000000E+01

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

As of right now the closest I have gotten in using iostream is

1.000000E+00

带有代码

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

有没有人知道最好的方法来获得前导零,如上所示,最好使用ostream而不是printf?

Does anyone know the best way to get a leading zero as shown above, preferably using ostream instead of printf?

推荐答案

正如我所说,您的要求是非标准的,但是您可以通过技巧来实现:

As I said, what you ask is non-standard, but you can achieve that with a trick:

#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 重新定义<< .

The Double wrapper is needed because you cannot redefine << for double.

我没有测试将指数 base 与浮点几率分开的方法,也许您可​​以想出一个更好的选择,但是您明白了:)

I did not test that way of separating exponent and base against the odds of floating point, maybe you can come up with a better alternative, but you get the idea :)

这篇关于使用C ++以1开头的零打印指数表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆