gpt4 book ai didi

c - 从 double 的格式说明符 '%g' 开始以指数格式打印

转载 作者:太空狗 更新时间:2023-10-29 15:21:32 25 4
gpt4 key购买 nike

我想了解 double 的格式说明符 %g 何时开始以指数格式打印值。

我的测试.c

#include <stdio.h>

int main() {

double val = 384615.38462;
double val2 = 9999999;
printf ("val = %g\n",val);
printf ("val2 = %g\n",val2);
return 0;
}

使用 gcc 编译:

gcc version 4.5.2 (GCC)
Target: i386-pc-solaris2.11

输出:

val = 384615
val2 = 1e+07

问题:为什么 val 打印为整数,为什么 val2 已转换为指数格式,即使我没有在 printf< 中使用 %lf/.

从何时开始使用指数格式打印值是否有一个范围?如果是,有什么办法可以猜出值的范围是多少?

提前致谢。

最佳答案

根据man 3 printf:

g, G

The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.

以及 C11 – ISO/IEC 9899:2011 标准草案 N1570 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf ):

g,G

A double argument representing a floating-point number is converted in style f or e (or in style F or E in the case of a G conversion specifier), depending on the value converted and the precision. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

— if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1).

— otherwise, the conversion is with style e (or E) and precision P − 1.

Finally, unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier.

关于c - 从 double 的格式说明符 '%g' 开始以指数格式打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38076102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com