printf中用%d输出float或者double

首先说一个“默认参数提升”的概念:

If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualied versionof its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.  -- C11 6.5.2.2  Function calls (6)

在可变长参数函数(例如printf函数)或者不带原型声明函数中,在调用该函数时C自动进行类型提升(在调用函数时如果声明这个函数那么则不会提升),提升如下:

——float类型的实际参数将提升到double
——char、short和相应的signed、unsigned类型的实际参数提升到int
——如果int不能存储原值,则提升到unsigned int
然后,调用者将提升后的参数传递给被调用者。C标准对默认实际参数提升规则有明确规定。也就是说, 带有可变长参数列表的函数, 绝对不会接受到char类型的实际参数。

相关链接:摸我摸我2摸我3

float a,b;
    a=1.2;
    printf("%d
",1.2);
    printf("%d",a);

如果是直接给1.2展示,那么结果是858993459,如果赋值给a来展示,那么结果为1073741824,why?

第一、1.2在内存中是以double类型存储的,具有64位的长度,但是%d输出时只能截取低32位进行输出。

第二、根据默认参数提升的概念,float类型的参数b被自动提升为double类型,这样也只能输出低32位。

但是a提升为double时和1.2在内存中默认存储不一样,导致了最后结果的不一样。


参考文章:C语言中的printf用%d输出float类型数据出现或以%f输出int型数据的结果为什么是0

                   printf("%d",5.01)和printf("%f",5)的输出结果

                   C语言函数参数传递之痛

原文地址:https://www.cnblogs.com/JSD1207ZX/p/9386259.html