简体   繁体   English

C科学计数法指数格式

[英]C scientific notation exponent format

Is it possible to control number of digits shown in exponent printed by scientific notation ( e ) of printf ? 是否可以控制用printf的科学记号( e )打印的指数中显示的位数?

This code 这段代码

#include <stdio.h>

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

produces (depends on compiler/platform): 产生(取决于编译器/平台):

4.030e+002 ( VS2010 ) or 4.030e+02 ( gcc 4.3.4 ) or even 4.030e+2 4.030e+002VS2010 )或4.030e+02gcc 4.3.4 )甚至4.030e+2

The different number of digits in exponents can easily confuse a diff tool when comparing files generated on different platforms. 比较不同平台上生成的文件时,指数中不同位数的数字很容易混淆diff工具。

You cannot do that with C printf() . 您不能使用C printf()来做到这一点。

According to C99 standard doc 7.19.6.1 for %e and %f : The 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 根据%e%f C99标准文档7.19.6.1: The 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 The 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

You could however, write your own wrapper function, where you calculate the base and exponent separately, to get the output in desired format. 但是,您可以编写自己的包装函数,在其中分别计算基数和指数,以获取所需格式的输出。

Something like: 就像是:

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

    //create the floating point string and return it 
}

Or you could manipulate the output of the printf %e to create your own string. 或者,您可以操纵printf %e的输出来创建自己的字符串。

The C standard actually specifies how many digits are to be in the exponent (WG14 N1570, §7.21.6.1/p8; N1256, §7.19.6.1/p8): C标准实际上指定了指数中的位数(WG14 N1570,§7.21.6.1/ p8; N1256,§7.19.6.1/ p8):

The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. 指数始终至少包含两位数,并且仅包含表示指数所需的更多位数。

VS2010's implementation is nonconforming. VS2010的实现不合格。 They do provide a library function to change the number of digits printed, which you can use inside a #ifdef wrapper. 它们确实提供了一种库功能来更改打印的位数,您可以在#ifdef包装器中使用该位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM