printf指定float的整数格式字符串

时间:2009-10-27 16:33:29

标签: c casting printf

#include <stdio.h>

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

这给出了输出:

0

为什么输出为零?

7 个答案:

答案 0 :(得分:13)

它不打印5,因为编译器不知道自动转换为整数。您需要自己(int)a

也就是说,

#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);
}

由于print_int的声明,编译器直接知道将float转换为int。

答案 1 :(得分:12)

%d格式说明符只能用于int类型的值。您正在传递doublefloat将被隐式转换为)。结果行为未定义。没有回答“为什么打印0?”题。任何东西都可以打印出来。事实上,任何事情都可能发生。

P.S。

  1. 那是int main,而不是void main
  2. 标准C中没有conio.h这样的标题。

答案 2 :(得分:5)

您应该将其强制转换为int以使用%d,或使用格式字符串显示不带小数精度的float:

void main() {
  float a=5;
  printf("%d",(int)a); // This casts to int, which will make this work
  printf("%.0f",a); // This displays with no decimal precision
}

答案 3 :(得分:5)

您需要使用%f代替%d - %d仅适用于整数,%f适用于浮点数:

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

答案 4 :(得分:4)

您必须使用不同的格式化字符串,只需查看即可 http://www.cplusplus.com/reference/clibrary/cstdio/printf/

printf(“%f”,a);

答案 5 :(得分:4)

您需要使用%f来打印浮点值。

例如

float a=5;
printf("%f",a);

答案 6 :(得分:1)

正如其他人所说,您需要在格式字符串中使用%f或将a转换为int。

但是我想指出你的编译器可能知道printf()的格式字符串,并且可以告诉你你错了。我的编译器通过适当的调用(-Wall包括-Wformat)表示:

$ /usr/bin/gcc -Wformat tmp.c
tmp.c: In function ‘main’:
tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’

$ /usr/bin/gcc -Wall tmp.c
tmp.c: In function ‘main’:
tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’

$

哦,还有一件事:你应该在printf()中包含'\ n'以确保输出被发送到输出设备。

printf("%d\n", a);
/*        ^^ */

或在fflush(stdout);之后使用printf()

相关问题