C語言基礎(chǔ)知識(shí):printf的輸出格式(MQL5照用)
作者:MT4 來源:cxh99.com 發(fā)布時(shí)間:2012年05月17日
- printf()函數(shù)是格式輸出函數(shù),請(qǐng)求printf()打印變量的指令取決與變量的類型.例如,在打印整數(shù)是使用%d符號(hào),在打印字符是用%c 符號(hào).這些符號(hào)被稱為轉(zhuǎn)換說明.因?yàn)樗鼈冎付巳绾尾粩?shù)據(jù)轉(zhuǎn)換成可顯示的形式.下列列出的是ANSI C標(biāo)準(zhǔn)peintf()提供的各種轉(zhuǎn)換說明.
轉(zhuǎn)換說明及作為結(jié)果的打印輸出%a 浮點(diǎn)數(shù)、十六進(jìn)制數(shù)字和p-記數(shù)法(C99)
%A 浮點(diǎn)數(shù)、十六進(jìn)制數(shù)字和p-記法(C99)
%c 一個(gè)字符
%d 有符號(hào)十進(jìn)制整數(shù)
%e 浮點(diǎn)數(shù)、e-記數(shù)法
%E 浮點(diǎn)數(shù)、E-記數(shù)法
%f 浮點(diǎn)數(shù)、十進(jìn)制記數(shù)法
%g 根據(jù)數(shù)值不同自動(dòng)選擇%f或%e.
%G 根據(jù)數(shù)值不同自動(dòng)選擇%f或%e.
%i 有符號(hào)十進(jìn)制數(shù)(與%d相同)
%o 無符號(hào)八進(jìn)制整數(shù)
%p 指針
%s 字符串
%u 無符號(hào)十進(jìn)制整數(shù)
%x 使用十六進(jìn)制數(shù)字0f的無符號(hào)十六進(jìn)制整數(shù)
%X 使用十六進(jìn)制數(shù)字0f的無符號(hào)十六進(jìn)制整數(shù)
%% 打印一個(gè)百分號(hào) 使用printf ()函數(shù) printf()的基本形式: printf("格式控制字符串",變量列表);
#include<cstdio>int main()
{
//for int
int i=30122121;
long i2=309095024l;
short i3=30;
unsigned i4=2123453; printf("%d,%o,%x,%X,%ld,%hd,%u\n",i,i,i,i,i2,i3,i4);//如果是:%l,%h,則輸不出結(jié)果
printf("%d,%ld\n",i,i2);//試驗(yàn)不出%ld和%d之間的差別,因?yàn)閘ong是4bytes
printf("%hd,%hd\n\n\n",i,i3);//試驗(yàn)了%hd和%d之間的差別,因?yàn)閟hort是2bytes
//for string and char
char ch1='d';
unsigned char ch2=160;
char *str="Hello everyone!";
printf("%c,%u,%s\n\n\n",ch1,ch2,str);//unsigned char超過128的沒有字符對(duì)應(yīng)
//for float and double,unsigned and signed can not be used with double and float
float fl=2.566545445F;//or 2.566545445f
double dl=265.5651445;
long double dl2=2.5654441454;
//%g沒有e格式,默認(rèn)6位包括小數(shù)點(diǎn)前面的數(shù),
//%f沒有e格式,默認(rèn)6位僅只小數(shù)點(diǎn)后面包含6位
//%e采用e格式,默認(rèn)6位為轉(zhuǎn)化后的小數(shù)點(diǎn)后面的6位
printf("%f,%e,%g,%.7f\n",fl,dl,dl,dl);
printf("%f,%E,%G,%f\n",fl,dl,dl,dl);//%F is wrong
printf("%.8f,%.10e\n",fl,dl);
printf("%.8e,%.10f\n\n\n",fl,dl);
//for point
int *iP=&i;
char *iP1=new char;
void *iP2;//dangerous!
printf("%p,%p,%p\n\n\n",iP,iP1,iP2);
//其他知識(shí):負(fù)號(hào),表示左對(duì)齊(默認(rèn)是右對(duì)齊);%6.3,6表示寬度,3表示精度
char *s="Hello world!";
printf(":%s: \n:%10s: \n:%.10s: \n:%-10s: \n:%.15s: \n:%-15s: \n:%15.10s: \n:%-15.10s:\n\n\n",
s,s,s,s,s,s,s,s); double ddd=563.908556444;
printf(":%g: \n:%10g: \n:%.10g: \n:%-10g: \n:%.15g: \n:%-15g: \n:%15.10g: \n:%-15.10g:\n\n\n",
ddd,ddd,ddd,ddd,ddd,ddd,ddd,ddd);
//還有一個(gè)特殊的格式%*.* ,這兩個(gè)星號(hào)的值分別由第二個(gè)和第三個(gè)參數(shù)的值指定 printf("%.*s \n", 8, "abcdefgggggg");
printf("%*.*f \n", 3,3, 1.25456f); return 0;