我正在通过K&R的C编程语言.这里在一个打印双变量的语句中写了
printf("\t%g\n", sum += atof(line));
Run Code Online (Sandbox Code Playgroud)
其中sum被声明为double.任何人都可以帮我解决何时使用%g的情况下双倍或浮动的情况,以及%g和%f之间的差异.
Dan*_*ill 36
它们都是浮点输入/输出的示例.
%g和%G是科学记数法浮点数%e和%E的简化符.
%g将采用可表示为%f(简单浮点数或双精度数)或%e(科学计数法)的数字,并将其作为两者中较短的一个返回.
print语句的输出将取决于sum的值.
unw*_*ind 27
请参阅任何参考手册,例如手册页:
F,F
double参数被舍入并在样式[ - ] ddd.ddd中转换为十进制表示法,其中小数点字符后面的位数等于精度规范.如果缺少精度,则取6; 如果精度明确为零,则不显示小数点字符.如果出现小数点,则在其前面至少出现一个数字.(SUSv2不知道F并且表示可以使用无穷大和NaN的字符串表示.C99标准指定'[ - ] inf'或'[ - ] infinity为无穷大,以及以'nan开头的字符串'对于NaN,在f转换的情况下,'[ - ] INF'或'[ - ] INFINITY'或'NAN*'在F转换的情况下.)
克,G
double参数以样式f或e(或G或E转换为G转换)转换.精度指定有效位数.如果精度丢失,则给出6位数字; 如果精度为零,则将其视为1.如果转换的指数小于-4或大于或等于精度,则使用样式e.尾随零从结果的小数部分中删除; 只有在后跟至少一位数字时才会出现小数点.
E = 指数表达式,简单来说就是幂(10, n) 或 10 ^ n
F = 分数表达式,默认6位精度
G = 一般表达式,以某种方式聪明地以简洁的方式显示数字(但真的吗?)
请参阅下面的示例,
代码
void main(int argc, char* argv[])
{
double a = 4.5;
printf("=>>>> below is the example for printf 4.5\n");
printf("%%e %e\n",a);
printf("%%f %f\n",a);
printf("%%g %g\n",a);
printf("%%E %E\n",a);
printf("%%F %F\n",a);
printf("%%G %G\n",a);
double b = 1.79e308;
printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
printf("%%e %e\n",b);
printf("%%f %f\n",b);
printf("%%g %g\n",b);
printf("%%E %E\n",b);
printf("%%F %F\n",b);
printf("%%G %G\n",b);
double d = 2.25074e-308;
printf("=>>>> below is the example for printf 2.25074*10^-308\n");
printf("%%e %e\n",d);
printf("%%f %f\n",d);
printf("%%g %g\n",d);
printf("%%E %E\n",d);
printf("%%F %F\n",d);
printf("%%G %G\n",d);
}
Run Code Online (Sandbox Code Playgroud)
输出
=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the example for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308
Run Code Online (Sandbox Code Playgroud)