返回信息流前两天回一个帖子的时候,说printf("%f")是用来处理double类型的,%lf是用来处理long double型的。
当时只查看了printf的男人,没有看scanf的男人。本着惩前毖后、治病救人的原则,来这里忏悔一下。
scanf和printf在对待这个问题上是有区别的。请同志们注意。
In printf(), the rvalue type promotions are expected. Thus %c actually corresponds to a parameter of type int and %f and %g actually correspond to parameters of type double.
Thus in printf() there is no difference between %f and %lf, or between %g and %lg.
However, in scanf() what is passed is a pointer to the variable so no rvalue type promotions occur or are expected.
Thus %f and %lf are quite different in scanf, but the same in printf.
见页
http://www.dgp.toronto.edu/~ajr/209/notes/printf.html
这是一条镜像帖。来源:北邮人论坛 / cpp / #30487同步于 2009/10/26
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
忏悔
ericyosho
2009/10/26镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
后面那段没看懂
我猜测一下,是因为scanf传的是个指针,大小是定的;而printf压栈,float就直接扩展到double了吗?
【 在 ericyosho (ericyosho) 的大作中提到: 】
: 前两天回一个帖子的时候,说printf("%f")是用来处理double类型的,%lf是用来处理long double型的。
: 当时只查看了printf的男人,没有看scanf的男人。本着惩前毖后、治病救人的原则,来这里忏悔一下。
: scanf和printf在对待这个问题上是有区别的。请同志们注意。
: ...................
恩,基本上是这么个意思。printf的话,被隐式和谐了,直接float就变成double了,所以没有区别,而且严格说来,如果使用%lf这样的写法,编译器应该会抛出warning的。
scanf需要明确的区分拿到的东东是double还是float,这里要是出错,就有点像C++里面的 static_cast 还有 reinterpret_cast。
【 在 ericyosho 的大作中提到: 】
: 前两天回一个帖子的时候,说printf("%f")是用来处理double类型的,%lf是用来处理long double型的。
: 当时只查看了printf的男人,没有看scanf的男人。本着惩前毖后、治病救人的原则,来这里忏悔一下。
: scanf和printf在对待这个问题上是有区别的。请同志们注意。
: ...................
好,学习一下~~
scanf 类型写错会很危险, %lf 8byte, %f 4 byte长度不一样,向内存写入的字节不一样
char a
float b;
scanf("%lf", &b);
gcc的话a直接就被覆盖了
【 在 jokerlee 的大作中提到: 】
: scanf 类型写错会很危险, %lf 8byte, %f 4 byte长度不一样,向内存写入的字节不一样
: char a
: float b;
: ...................
不单在gcc,绝大部分的编译器基本都会被覆盖掉,溢出了~~