首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言字符轉大寫:條件判寫法導致邏輯錯誤修正

     編輯:程式設計綜合問答

錯誤代碼

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;
}

總結

  • C/C++ 不支持鏈式比較 a <= x <= b,必須拆分為 a <= x && x <= b。
  • 優先使用 ctype.h 中的 toupper/tolower,避免硬編碼 ASCII 差值。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved