トリック"
printf("%c", '0'+5);
出力を取得する5
ための (10 進数の) 数字、つまり 0 ~ 9 に対してのみ機能します。printf("%c", '0'+10)
出力を与えます:
。なんで?
printf("%c",..)
単一の文字を印刷するためのものです。各文字には数値コードがあります ( ASCII コードを参照)。65 は の ASCII コードA
なのでprintf("%c", 65)
、この文字を与えます。printf("%c", 48)
を与えます0
。C 言語では'0'
の代わりに書くことができる48
ので、ASCII コードを覚える必要はありません。C コンパイラは、任意の文字を対応する ASCII コードに変換し''
ます""
。したがって、上記のコード行は次と同じです
printf("%c", 48+5);
int を文字列表現に変換するには、次のように C で行うことができます。
char repr[12]; // a 32-bit int has at most 10 digits;
// +1 for possible sign; +1 for closing 0-character ("null termination")
sprintf(repr, "%d", 10101); // prints the number into a string
itoa(10101, repr, 10); // does the same thing
printf("%s", repr); // prints the string representing the number
printf("%d", 10101); // does the same thing directly