为什么printf的隐含浮到int转换不行? [英] Why does printf implicit float to int conversion not work?

查看:115
本文介绍了为什么printf的隐含浮到int转换不行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我理解下面的C输出:

Please help me in understanding the following C Output:

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

输出继电器上的gcc编译器

Ouput on gcc compiler

4.000000
0
4

至于当我们分配浮到变量int变量的小数部分被终止,然后分配给INT我读

As far as i have read when we assign float to an int variable the decimal part of the variable is terminated and then assigned to the int.

为什么它不是在这种情况下发生?

Why it is not happening in this case?

推荐答案

您不是打印,你打印 X 试。

You're not printing y, you're printing x again.

作为一个方面说明, 的printf 不能做转换。因此,通过一个浮动时,%d个预期是不确定的行为。

As a side note, printf can't do conversions. So passing a float when a %d is expected is undefined behavior.

这篇关于为什么printf的隐含浮到int转换不行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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