2014-02-07 67 views
1

我從The C Programming Language,Second Edition學習C語言。其中有以下代碼:C數組推,爲什麼減去'0'?

#include <stdio.h> 

/* count digits, white space, others */ 
main() { 
    int c, i, nwhite, nother; 
    int ndigit[10]; 

    nwhite = nother = 0; 
    for (i=0; i<10; ++i) { 
     ndigit[i] = 0; 
    } 

    while ((c = getchar()) != EOF) { 
     if (c >= '0' && c <= '9') { 
      ++ndigit[c-'0']; 
     } 
     else if (c == ' ' || c == '\n' || c == '\t') { 
      ++nwhite; 
     } 
     else { 
      ++nother; 
     } 
    } 

    printf("digits ="); 
    for (i=0; i<10; ++i) { 
     printf(" %d", ndigit[i]); 
    } 

    printf(", white space = %d, other = %d\n", nwhite, nother); 
} 

現在,我可以理解這段代碼在做什麼。它計算每個數字在輸入中出現的次數,然後將該數字放入數字的索引中,即11123 = 0 3 1 1 0 0 0 0.我只是好奇它的1行:

++ndigit[c-'0']; 

這會將數組的索引c加1,但爲什麼它會從c中減去0?當然,這沒有意義,對嗎?

+0

''0''不是'0'。 – SLaks

+1

這並非毫無意義。這是將字符數字轉換爲int的簡單方法。 – cnicutar

+0

只需c將索引數組[48 57]。 c-'0'會將其降至[0 9]。 – tommyo

回答

3

表達式c - '0'正在從一個數字的字符表示轉換爲相同數字的實際整數值。例如,它的炭'1'轉換成整數1

我想有一點更有意義的完整的例子來看看這裏

int charToInt(char c) { 
    return c - '0'; 
} 

charToInt('4') // returns 4 
charToInt('9') // returns 9 
+0

啊,我明白了。看起來很明顯,當你這樣說。謝了哥們! – dboxall123

1

它不減去零......它減去字符'0'的ASCII值。

這樣做會爲您提供數字的序號值,而不是其ASCII碼錶示。換句話說,它將字符'0'到'9'分別轉換爲數字0到9。