c - 将整数打印为 float

标签 c floating-point

<分区>

Possible Duplicate:
What is printf’s behaviour when printing an int as float?

int main()
{
 int x=4;
 int y=987634;
 printf("%f %f",x,y);
}

编译此代码时,我得到的输出为 0.000000 0.000000。不应该将 x 和 y 类型提升为 float 吗? O/P 不应该是 4.000000 和 987634.000000 吗? 谁能帮我这个。提前致谢。

最佳答案

转换发生在带有包含特定参数的原型(prototype)的函数的参数上。 printf() 的原型(prototype)不包含第一个之后的具体参数

int printf(const char *format, ...);

因此,第一个参数之后的参数不会自动转换,除非由“默认参数转换”定义(基本上任何等级低于 intint 的整数类型以及等级低于 doubledouble 的任何浮点类型(谢谢您,Pascal Cuoq))。您需要自己使用强制转换操作显式转换它们

    printf("%f %f\n", (double)x, (double)y);

哦......你真的,真的,真的应该包括有问题原型(prototype)的标题(在未定义行为的惩罚下)

#include <stdio.h>

关于c - 将整数打印为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588973/

相关文章:

javascript - 如何在 JavaScript 中只舍入 float 数字?

c - 为什么 5.0/3 在 C 中是 1.666667?

c - 编译器如何处理 OpenMP 指令

C 如何释放多维动态结构中的动态字符串?

c - 如何用C读取一个.CAP文件?

c - 缓冲区溢出 : EIP and jump correctly set but segfault

c - 转发声明到指向结构的指针数组搞砸了?

c - Lua - lua_tostring() 返回奇怪的结果

c++ - 如何打印完整的 float 而不是 "1.01383e+007"?

math - float 学坏了吗?