为什么printf()用%f输出double型,而scanf却用%lf呢?

本文解释了printf和scanf函数中%f与%lf的区别,并详细列出了这两个函数支持的各种格式说明符及其对应的参数类型。

之前没有注意过这个问题,  转自: http://book.51cto.com/art/200901/106880.htm

问:有人告诉我不能在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。)

另外, 关于才c++标准输入输出同步, 如果是用了ios::sync_with_stdio(false)的话是可以达到近似scanf的速度的。

static void sync_with_stdio();
Synchronizes the C++ streams with the standard I/O system. The first time this function is called, it resets the predefined streams (cincoutcerrclog) to use astdiobuf object rather than a filebufobject. After that, you can mix I/O using these streams with I/O using stdinstdout, and stderr. Expect some performance decrease because there is buffering both in the stream class and in the standard I/O file system.
After the call to sync_with_stdio, the ios::stdio bit is set for all affected predefined stream objects, and cout is set to unit buffered mode.

转载于:https://www.cnblogs.com/Stomach-ache/p/3726444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值