printf为浮点数指定整数格式的字符串

#include <stdio.h>


int main()

{

    float a = 5;

    printf("%d", a);

    return 0;

}

这给出了输出:


0

为什么输出为零?


ABOUTYOU
浏览 545回答 3
3回答

慕姐4208626

它不会打印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);}由于的声明,编译器直接知道将float转换为int的位置print_int。

倚天杖

正如其他人所说,您需要使用%f格式字符串或将其转换a为int。但我想指出的是,您的编译器可能知道printf()的格式字符串,并且可以告诉您您使用的格式错误。经过适当调用(-Wall包括-Wformat)的我的编译器说:$ /usr/bin/gcc -Wformat tmp.ctmp.c: In function ‘main’:tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’$ /usr/bin/gcc -Wall tmp.ctmp.c: In function ‘main’:tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’$哦,还有另一件事:您应该在中包含'\ n',printf()以确保将输出发送到输出设备。printf("%d\n", a);/*&nbsp; &nbsp; &nbsp; &nbsp; ^^ */或fflush(stdout);在printf()。之后使用。
打开App,查看更多内容
随时随地看视频慕课网APP