在 C 中将浮点数打印为整数并将整数打印为浮点数时的奇怪输出 [英] strange output while printing float as integer and integer as float in C

查看:93
本文介绍了在 C 中将浮点数打印为整数并将整数打印为浮点数时的奇怪输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码没有显示预期的输出是垃圾值(奇怪的是这些值被交换了)

the following code is not showing the expected output which is garbage value ( strangely the values are swapped )

#include<stdio.h>
int main()
{
    float f = 4.6;
    int d = 7;
    printf("%d %f\n",f,d);
    return 0;
}

输出:7 4.600000

output: 7 4.600000

推荐答案

让我们减少一点:

float f = 4.6;
printf("%d\n", f);

这是未定义的行为.必须为正确的格式说明符提供正确类型的参数.

That's undefined behavior. The correct format specifier must be given an argument of the correct type.

未定义的行为可能导致任何结果,包括您所看到的这种奇怪的结果.

Undefined behavior can cause any outcome, including this odd outcome that you are seeing.

现在,您可能会问为什么编译器甚至会生成此代码.那么让我们看看 x86-64 程序集的 2 个代码:

Now, you might be asking why a compiler would even produce this code. So let's look at the x86-64 assembly for 2 codes:

int main() {
    float f = 4.6;
    int d = 7;
    printf("%d %f\n", d, f);
    return 0;
}

int main() {
    float f = 4.6;
    int d = 7;
    printf("%f %d\n", f, d);
    return 0;
}

除了格式字符串,这两个代码产生相同的程序集.这可能是因为调用约定要求将浮点数放置在与整数不同的寄存器中,或者应该将浮点数传递到堆栈中(或任何其他以不同方式处理浮点数和整数的规则).

Other than the format string, these two codes produce identical assembly. This is likely because the calling convention requires floats to be placed in different registers than integers, or that floats should be passed on the stack (or any number of other rules that handle floats and integers differently).

这应该更清楚为什么您发布的代码仍然产生有用的东西,即使代码刚刚损坏.

This should make it clearer why the code you posted is still producing something useful, even though the code is just broken.

这篇关于在 C 中将浮点数打印为整数并将整数打印为浮点数时的奇怪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆