printf中用%d输出float或者double

本文探讨了C语言中printf函数使用%d格式化符处理float或double类型参数时的类型提升规则。当float参数被提升为double,%d只会显示低32位,导致输出可能不符合预期。同时解释了不同类型参数在内存中的存储和转换差异。
摘要由CSDN通过智能技术生成

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

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类型的实际参数。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值