puts 僅輸出字符串,自動換行。printf(print format)功能強大:輸出整數、小數、字符、字符串,格式可控(進制、寬度、精度)。
printf("C語言中文網"); // 同 puts 效果
int abc = 999;
printf("%d", abc); // %d 佔位符,輸出十進制整數
printf("The value of abc is %d !", abc); // 字符串混合輸出
輸出:
The value of abc is 999 !
int a=100, b=200, c=300;
printf("a=%d, b=%d, c=%d", a, b, c);
輸出:
a=100, b=200, c=300
%d 為格式控制符,以 % 開頭,與後續變量**一一對應**。
| 控制符 | 含義 | 來源 |
|---|---|---|
| %d | 十進制整數 | decimal |
| %c | 單字符 | character |
| %s | 字符串 | string |
| %f | 小數 | float |
#include <stdio.h>
int main() {
int n = 100;
char c = '@';
float money = 93.96;
printf("n=%d, c=%c, money=%f\n", n, c, money);
return 0;
}
輸出:
n=100, c=@, money=93.959999
\n 換行,puts 自動換行,printf 需手動加。// 後為註釋,編譯器忽略。money 輸出非精確 93.96,因浮點數二進制存儲近似值,詳見《小數在內存中是如何存儲的》。printf("n=%d, c=%c, money=%f\n", 100, '@', 93.96);
無需變量,直接用常量。
int a = 1234;
printf("a=%ds\n", a);
輸出:
a=1234s
%d 是格式符,s 只是緊隨其後的普通字符,無特殊含義。