有关lf说明符的scanf()和带有lf说明符的printf()的问题?
我正在学习C,我有以下代码:
#include #include #include int main(int argc, char *argv[]) { double x; printf("x = "); scanf("%ld", &x); printf("x = %lf\n", x); system("PAUSE"); return 0; }
(我使用的是Dev C4.9,Windows XP SP3)
当我运行上述程序并进入5.3; 程序打印x = 0.000000
谁能解释为什么会这样,拜托?
非常感谢。
%ld
格式字符串意味着它期望读取long signed int
,但是你传递它而不是double
。 您应该使用%lf
格式说明符来表示您想要一个double
。
请注意,对于scanf
, l
需要double
s(并且要求float
不存在),而对于printf
, %lf
的l
无效: %f
和%lf
对两个float
都有相同的输出s和double
s,由于默认参数提升。
为您的scanf
ld:
same as "%d" except argument is "long" integer. Since "long" is the same as "int" on GCOS8,this is the same as "%d". However, the compiler will warn you if you specify "%ld" but pass a normal "int", or specify "%d" but pass a "long".
为你的printf
lf:
same as "%f" except argument is "long double". Since "long double" is the same as "double" on GCOS8, this is the same as "%f".
读这个。
与scanf和printf的数据保持一致。 再加上%lf(double),%f(浮动),%lld(long long int)我在windows中遇到了问题。 它在Windows中没有很好地实现(msvcrt.dll,如果你问)。
最好使用gets()
然后尝试解析并将输入的字符串转换为所需的类型。
因为所有内容最初都是作为字符串输入的,所以更容易处理错误的输入。
scanf要求输入是完美的,并且当人类输入数据时并不总是这样。