我正在生成一个文本文件,用作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吗?
答案 0 :(得分:1)
C想:
不是很好的答案,因为C ++的答案首选。
char buf[20];
buf[0] = ' ';
double x = -1.234567;
sprintf(&buf[1], "% .6E", x*10);
if (buf[3] == '.') { // detect if x was INF or NAN
buf[0] = buf[1];
buf[1] = '0';
buf[3] = buf[2];
buf[2] = '.';
}
// Cope with leading potential space if needed
if (buf[0] == ' ') memmove(&buf[0], &buf[1], strlen(buf));
printf("%s\n", buf);
// -0.1234567E+00
弱点:小数点不是'。'时出现问题。或者在INF附近x。
答案 1 :(得分:1)
正如我所说,你问的是非标准的,但你可以通过一个技巧实现这一点:
#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
。
我没有测试那种将exponent
和base
与浮点数分开的方法,也许你可以提出一个更好的选择,但你明白了这一点:)
答案 2 :(得分:0)
cout << "0." << setprecision(6) << fixed << scientific << uppercase << number * 10;
答案 3 :(得分:-1)
printf ("%2.2f %+.0e %E \n", 2.016, 1.226, 0.1416);
输出:2.02 + 1e + 000 1.416000E-001