printf的指定浮点整数格式字符串 [英] printf specify integer format string for float

查看:143
本文介绍了printf的指定浮点整数格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main()
{
    float a = 5;
    printf("%d", a);
    return 0;
}

这给出了输出:

0

为什么输出为零?

Why is the output zero?

推荐答案

这不打印5,因为编译器不知道要自动转换为整数。你需要做的(INT)一自己。

It doesn't print 5 because the compiler does not know to automatically cast to an integer. You need to do (int)a yourself.

也就是说,

#include<stdio.h>
void main()
{
float a=5;
printf("%d",(int)a);
}

正确输出5。

相比之下,程序与

#include<stdio.h>
void print_int(int x)
{
printf("%d\n", x);
}
void main()
{
float a=5;
print_int(a);
}

其中,直接编译知道要浮动转换为一个int,由于申报 print_int

这篇关于printf的指定浮点整数格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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