C語言基礎知識:printf的輸出格式

來源:互聯網
上載者:User
printf()函數是格式輸出函數,請求printf()列印變數的指令取決與變數的類型.例如,在列印整數是使用%d符號,在列印字元是用%c 符號.這些符號被稱為轉換說明.因為它們指定了如何不資料轉換成可顯示的形式.下列列出的是ANSI C標準peintf()提供的各種轉換說明.
 
          轉換說明及作為結果的列印輸出%a                浮點數、十六進位數字和p-記數法(C99)
%A    浮點數、十六進位數字和p-記法(C99)
%c    一個字元 
%d    有符號十進位整數 
%e    浮點數、e-記數法
%E    浮點數、E-記數法
%f    浮點數、十進位記數法  
%g    根據數值不同自動選擇%f或%e.
%G    根據數值不同自動選擇%f或%e.
%i               有符號十進位數(與%d相同)
%o    無符號八進位整數
%p    指標    
%s    字串
%u    無符號十進位整數
%x    使用十六進位數字0f的無符號十六進位整數 
%X    使用十六進位數字0f的無符號十六進位整數
%%    列印一個百分比符號  使用printf ()函數 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,則輸不出結果
    printf("%d,%ld\n",i,i2);//實驗不出%ld和%d之間的差別,因為long是4bytes
    printf("%hd,%hd\n\n\n",i,i3);//實驗了%hd和%d之間的差別,因為short是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的沒有字元對應
        //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格式,預設6位包括小數點前面的數,
    //%f沒有e格式,預設6位僅只小數點後麵包含6位
    //%e採用e格式,預設6位為轉化後的小數點後面的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);
   
    //其他知識:負號,表示靠左對齊(預設是靠右對齊);%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);    //還有一個特殊的格式%*.* ,這兩個星號的值分別由第二個和第三個參數的值指定    printf("%.*s \n", 8, "abcdefgggggg");
    printf("%*.*f   \n", 3,3, 1.25456f);     return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.