在 C 中将 int 打印为浮点数 [英] Printing int as float in C
问题描述
我正在为 Little Endian 使用 Visual Studio TC 编译器.下面是一段代码:
I'm using Visual Studio TC compiler for Little Endian. The following is the piece of code:
void main()
{
float c = 1.0;
int a = 0x3F800000;
int *ptr = (int *)&c;
printf("\n0x%X\n", *ptr);
printf("\na = %f", a);
printf("\nc = %f", c);
return;
}
输出为:
0x3F800000
a = 0.000000
c = 1.000000
浮点值 1.0 是 0x3F800000,在 Little Endian 的内存中存储为 00 00 80 3F.相同的值被分配给 int a.printf 如何为 int 打印 0.000000 而为 float c 打印 1.000000?我已经看到它在 printf 中使用 %f 打印时将所有整数值打印为 0.000000.
Float value 1.0 is 0x3F800000 and stored as 00 00 80 3F in memory for Little Endian. The same value is assigned to int a. How printf prints 0.000000 for int a while 1.000000 for float c? I've seen it prints all integer values as 0.000000, when printed using %f in printf.
另外,由于printf是可变参数函数,它怎么知道寄存器中传入的值是int还是float?
Also, since printf is variable argument function, how does it knows whether the passed value in the register is int or float?
推荐答案
我的超能力告诉我 Adam Liss 的评论是正确答案:float
参数被提升为 double
,所以 printf()
函数期望发生这种情况:它期望堆栈上有 64 位值,但得到 32 位加上恰好为零的垃圾数据.
My psychic powers tell me Adam Liss's comment is the right answer: float
arguments are promoted to double
, so the printf()
function expects that to happen: It expects a 64-bit value on the stack, but gets 32 bits plus garbage data that happen to be zero.
如果增加显示精度,显示应该类似于a = 0.00000000001
.
If you increase the display precision, the display should be something like a = 0.00000000001
.
这也意味着这应该有效:
This also means this should work:
void main()
{
double c = 1.0;
long long a = 0x3FF0000000000000;
long long *ptr = (long long *)&c;
printf("\n0x%llX\n", *ptr);
printf("\na = %f", a);
printf("\nc = %f", c);
return;
}
这篇关于在 C 中将 int 打印为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!