Scanf没有读取双倍
我试图使用scanf
连续读取用户的double
值。
码:
printf("Enter A value: \n"); double input; int result = scanf("%f", &input); printf("INPUT: %f\n", input);
输出是
INPUT: 0.000
你骗了编译器:扫描时, %f
表示你提供了一个float
指针。 但是你提供了一个指向double
的指针。
要修复,请使用%lf
或将 input
声明为float
。
请注意, printf
格式存在不对称性,对于float
和double
参数都使用%f
。 这是有效的,因为printf
参数被提升为double
(并且不是指针)。
我试图使用scanf 连续读取用户的双倍值。
为此,您需要一个循环,如下所示:
while(scanf("%lf", &input) == 1) { //code goes here... printf("INPUT: %lf\n", input); //code goes here... }
请注意,由于input
的基本类型是double
,因此需要使用%lf
而不是%f
( %f
用于float
)。