亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問printf為浮點數指定整數格式的字符串

請問printf為浮點數指定整數格式的字符串

C
幕布斯6054654 2020-01-06 08:00:00
#include <stdio.h>int main(){    float a = 5;    printf("%d", a);    return 0;}這給出了輸出:0為什么輸出為零?
查看完整描述

3 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

它不會打印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。



查看完整回答
反對 回復 2020-01-07
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

正如其他人所說,您需要使用%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’


$

哦,還有另一件事:您應該在中包含'\ n',printf()以確保將輸出發送到輸出設備。


printf("%d\n", a);

/*        ^^ */

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



查看完整回答
反對 回復 2020-01-07
  • 3 回答
  • 0 關注
  • 536 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號