每個ASCII字符都有一個整數值。打印字符時,下層系統檢查變量值char
並打印相應的ASCII字符。值本身不打印。請參閱ASCII table以供參考。
char var = '7'; // var's value is actually 55.
char other = 55; // This is same as '7'
當計算兩個數字字符的總和,你的情況「5」和「7」,你必須減去字符「0」,從他們皈依「5」和「7」,以數字5和7。
char first = '5' - '0'; // Is actually 53 - 48 = 5
char second = '7' - '0'; // Is actually 55 - 48 = 7
char result = first + second; // 5 + 7 = 12
// When you print result, you will not see "12" printed. Instead you see a form feed special character.
char test = '5' + '7'; // 53 + 55 = 108, which is letter 'l'
你要的char
值轉換爲字符串打印的實際值。你可以用itoa()
轉換。
char result = ('5' - '0') + ('7' - '0');
char buf[5];
memset(buf, 0, sizeof(buf));
itoa((int)result, buf, 10);
printf("%s\n", buf);
這是怎樣的問題,如果你擴大你的代碼,一個完整的計劃,我們可以只複製和粘貼,以編譯和運行, – hugomg
,這將大大受益?我使val爲0x12 - 換頁符。 –
@MartinJames不是'0x12'而是十進制'12'。 –