prinf scanf 格式控制【注意double】

来源:互联网 发布:js小游戏 编辑:程序博客网 时间:2024/05/23 11:27

ref:《你必须知道的495个C语言问题》

问:有人告诉我不能在printf中使用%lf。为什么printf()用%f输出double型,而scanf却用%lf呢?

答:printf的%f说明符的确既可以输出float型又可以输出double型。 根据"默认参数提升"规则(在printf这样的函数的可变参数列表中 ,不论作用域内有没有原型,都适用这一规则)float型会被提升为double型。因此printf()只会看到双精度数。参见问题15.2。

对于scanf,情况就完全不同了,它接受指针,这里没有类似的类型提升。(通过指针)向float存储和向double存储大不一样,因此,scanf区别%f和%lf。

下表列出了printf和scanf对于各种格式说明符可以接受的参数类型。

格式

printf

scanf

%c

int

char *

%d, %i

int

int *

%o, %u, %x                               

unsigned int                                   

unsigned int *                                      



格式

printf

scanf

%ld, %li

long int

long int *

%lo, %lu, %lx

unsinged long int

unsigned long int *

%hd, %hi

int

short int *

%ho, %hu, %hx

unsigned int

unsigned short int *

%e, %f, %g

double

float *

%le, %lf, %lg

n/a

double *

%s

char *

char *

%[...]

n/a

char *

%p

void

void **

%n

int *

int *

%%

none

none


(严格地讲,%lf在printf下是未定义的,但是很多系统可能会接受它。要确保可移植性,就要坚持使用%f。)
参见问题12.15和15.2。
参考资料: [18, Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-150]
[19, Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-159]
[35, Sec. 4.9.6.1, Sec. 4.9.6.2]
[8, Sec. 7.9.6.1, Sec. 7.9.6.2]
[11, Sec. 15.8 pp. 357-364, Sec. 15.11 pp. 366-378]
[22, Sec. A.1 pp. 121-133]
原创粉丝点击