scanf 和 double 的问题 [英] Problems with scanf and doubles
问题描述
我无法理解为什么会发生这种情况:使用以下代码;
im having trouble understanding why this occurs: with the following code;
#include <stdio.h>
int main()
{
double x=123;
printf("x is %f. Enter a new value for x.\n", x);
scanf("%f", &x);
printf("x is %f\n", x);
return 0;
}
当您输入 45678 作为 x 的新值时,将打印x is 123.000017".我知道当你在扫描时使用 %lf 时这是固定的,但为什么在使用 %f 时会发生这种情况?
when you enter 45678 as the new value for x, 'x is 123.000017' is printed. I know that this is fixed when you use %lf when scanning, but why does this happen when using %f?
推荐答案
我知道当你在扫描时使用 %lf 时这是固定的,但为什么在使用 %f 时会发生这种情况?
I know that this is fixed when you use %lf when scanning, but why does this happen when using %f?
printf
和 scanf
函数参数之间的区别在于您将值传递给 printf
,但传递给 scanf
您传递指针(即值的地址).根据 C 规则,当一个函数接受可变数量的参数时,所有参数都会经历默认提升.
The difference between printf
and scanf
function arguments is that you pass values to printf
, but to scanf
you pass pointers (i.e. addresses of values). According to C rules, when a function takes a variable number of arguments, all parameters undergo default promotions.
其中一项促销是 float
转换为 double
,与 short
转换为 的方式相同整数
.这就是为什么您可以将 %f
或 %lf
与 printf
一起使用:这两种类型的值都被编译器转换为 double
,因此访问它们是安全的.
One of the promotions is that float
s get converted to double
, in the same way that short
s get converted to int
. That is why you can use %f
or %lf
with printf
: both types of values are converted by the compiler to double
, so accessing them is safe.
但是,指针没有这样的规则(并且有一个很好的理由:尝试将 double
写入 float
的空间将是未定义的行为).这就是为什么在将参数传递给 scanf
系列函数时必须区分 %f
和 %lf
的原因.
However, there is no such rule for pointers (and for a good reason: trying to write a double
into a space of float
would be undefined behavior). That is why you must differentiate between %f
and %lf
when passing parameters to the scanf
family of functions.
这篇关于scanf 和 double 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!