printf()中的浮点格式

sfa*_*tor 8 c floating-point floating-accuracy

我有花车的数组,其中数据存储与不同的小数点所以有的123.40000,123.45000,123.45600...现在如果我要在打印字符串中的这些值,而不到底0 printf(),让自己123.4,123.45,123.456,没有那些0到底.这可能吗?如果是这样,怎么样?

小智 18

使用%g格式化程序:

printf( "%g", 123.4000 );
Run Code Online (Sandbox Code Playgroud)

版画

123.4

删除尾随零,但不幸的是,如果小数部分为零,则尾随小数点也是如此.我不知道是否有任何方法可以直接使用printf()做你想做的事情 - 我觉得这样的事情可能是你最好的选择:

#include <stdio.h>
#include <math.h>

void print( FILE * f, double d ) {
    if ( d - floor(d) == 0.0 ) {
        fprintf( f, "%g.", d );
    }
    else {
        fprintf( f, "%g", d );
    }
}

int main() {
    print( stdout, 12.0 );
    print( stdout, 12.300 );
}
Run Code Online (Sandbox Code Playgroud)