15

In C, is there any difference in the format specifiers %f, %e, %g, %E and %G when used to read into a float variable with scanf? That is, will the behaviour of the code snippet

float x;
scanf("%<one of f, e, g, E, G>", &x);

ever depend on the choice of the specifier?

I first supposed that %f would only interpret decimal notation correctly, and %e would only interpret scientific notation correctly, but on my system, each of them works fine in either case. But maybe my system is just liberal...

I couldn't find any definite statement about this in my books or on the web...

4

6 回答 6

11

上面的答案是指 C++,但 C 也是如此。

来自“包含更正 TC1、TC2 和 TC3 的 C99 标准的最终版本,格式化为草稿”中的“7.19.6.2 fscanf 函数” (链接复制自http://en.wikipedia.org/wiki/C99 ):

a,e,f,g
匹配可选带符号的浮点数、无穷大或 NaN,其格式与 strtod 函数的主题序列的预期格式相同。相应的参数应该是一个指向浮动的指针。

转换说明符A、E、F、GX也是有效的,它们的行为分别与a、e、f、gx相同。

因此,正如您所经历的那样,在扫描数字%f, %e, %g, %E, %G时,所有人的行为都相同。

于 2013-11-10T20:49:24.720 回答
2

f,e,g都是浮点数

来自文档:-

一系列十进制数字,可选地包含一个小数点,可选地前面有一个符号(+ 或 -),可选地后跟 e 或 E 字符和一个十进制整数(或 strtod 支持的一些其他序列)。符合 C99 的实现也支持以 0x 或 0X 开头的十六进制浮点格式。

还要检查this reference,它说it( f,e,g)匹配一个浮点数。

于 2013-11-10T20:07:27.667 回答
1

C 将 float 和 double 变量显示到小数点后六位。printf()这并不是指实际存储数字的精度(准确度),而是指用于显示这些变量类型的小数位数。

以下程序说明了如何声明和显示不同的数据类型:

#include <stdio.h>

main()
{

    float   a = 23.567;
    double  b = 11e+23;

    printf("Float variable is %f\n", a);
    printf("Double variable is %e\n", b);
}

输出

Float variable is 23.567000
Double variable is 11.000000e23
于 2015-11-26T10:32:43.790 回答
1

%f将数字打印为十进制浮点数,例如 214.52。%e以科学计数法打印数字,例如 214.52e+2。%g打印两个中最短的数字,例如在上面的两个示例中,如果我想通过 %g 打印数字,那么它将是 214.52 而不是 2.145e+2 因为它更长。

#include<stdio.h>
int main(int argc, char *argv[]) {
    float f=214.52;   
    printf("%f\n",f); // 214.520004
    printf("%e\n",f); // 2.145200e+02
    printf("%g\n",f); // 214.52
}
于 2018-07-03T06:17:48.770 回答
0

基于@Sameer Sharma 的回答

$ cat test.c 
#include<stdio.h>
void main()
{

float f=12.5123;

    printf("%f\n",f);
    printf("%e\n",f);
    printf("%g\n",f);
}

$ gcc test.c
$ ./a.out
12.512300
1.251230e+01
12.5123
于 2020-01-16T06:58:30.987 回答
-1
%i=defaults for decimals
%u=gives the memory address of the variable
%p=gives the value of pointer
%e=gives the scientific notation
%g=handles large floating numbers
于 2015-08-29T11:29:17.597 回答