if (97 <= aa[i] <= 122) aa[i] -= 32;
C 語言中 97 <= aa[i] <= 122 並不會按數學意義鏈式比較,而是按運算符結合性從左至右執行:
(97 <= aa[i]) <= 122。
97 <= aa[i] 的結果是 0 (假) 或 1 (真),這個 0/1 再與 122 比較,恆為真 (1 <= 122),導致所有字符(包括大寫、符號)都被減 32,產生亂碼。
if (97 <= aa[i] && aa[i] <= 122) aa[i] -= 32;
// 或使用標準庫函數
#include <ctype.h>
aa[i] = toupper(aa[i]);
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char aa[] = "Hello world";
int len = strlen(aa);
for (int i = 0; i < len; i++) {
aa[i] = toupper(aa[i]); // 推薦:可移植、處理非 ASCII
}
printf("%s\n", aa); // HELLO WORLD
return 0;
}
a <= x <= b,必須拆分為 a <= x && x <= b。ctype.h 中的 toupper/tolower,避免硬編碼 ASCII 差值。