C科学符号指数格式

时间:2014-07-30 06:24:21

标签: c printf

是否可以控制用printf的科学记数法(e)打印的指数中显示的位数?

此代码

#include <stdio.h>

int main(void) {
    printf("%6.3e", 403.0);
    return 0;
}

生成(取决于编译器/平台):

4.030e+002VS2010)或4.030e+02gcc 4.3.4)或4.030e+2

在比较不同平台上生成的文件时,指数中不同的位数很容易混淆diff工具。

2 个答案:

答案 0 :(得分:3)

你不能用C printf()做到这一点。

根据C99标准doc 7.19.6.1对%e%fThe exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. If the value is zero, the exponent is zero

然而,您可以编写自己的包装函数,分别计算基数和指数,以获得所需格式的输出。

类似的东西:

char* printexponent(double x)
{
    //calculate base here
    //calculate exponent here

    //create the floating point string and return it 
}

或者您可以操作printf %e的输出来创建自己的字符串。

答案 1 :(得分:2)

C标准实际上指定了指数中的位数(WG14 N1570,§7.21.6.1/ p8; N1256,§7.19.6.1/ p8):

  

指数始终包含至少两位数字,并且只包含表示指数所需的位数。

VS2010的实施不合规。它们确实提供library function来更改打印的位数,您可以在#ifdef包装内使用。