2011-05-14 43 views
0

我編寫函數計算字符串中的數字。 示例: 「t5ds5」 程序返回10 = 5 + 5。 我運行我的程序時出錯。 這裏的代碼!函數計算字符串中的數字

int SumStr(char *str) 
{ 
    int i; 
    int temp = 0; 
    for(i=0;i<strlen(str);i++) 
    { 
     if(*str >= 48 && *str <= 57) 
     { 
      temp +=*str; 
     } 
    } 
    printf("%d", temp); 
    return 0; 
} 
+2

你會得到什麼錯誤? – 2011-05-14 18:16:44

+0

在strlen函數中出現訪問衝突錯誤。 – Wl7a 2011-05-14 18:18:37

+2

最好使用['isdigit()'](http://linux.die.net/man/3/isdigit)來檢查數字字符。 – 2011-05-14 18:19:11

回答

2

您不會將指針移動到字符串,因此您只會檢查第一個值,而不會檢查其他任何值。您還需要從ascii值向下移到整數值。它應該是這樣的:

if (str[i] >= 48 && str[i] <= 57) { 
    temp += str[i] - '0'; 
} 
+0

仍然有錯誤 – Wl7a 2011-05-14 18:25:10

2

試試這個:

int SumStr(char *str) 
{ 
    int temp = 0; 
    while(*str) 
    { 
     if((*str >= '0') && (*str <= '9')) 
      temp += *str - '0'; 
     str++; 
    } 
    printf("%d", temp); 
    return 0; 
} 

雖然這會顯得更加正常:

int SumStr(char *str) 
{ 
    int result = 0; 
    while(*str) 
    { 
     if((*str >= '0') && (*str <= '9')) 
      temp += *str - '0'; 
     str++; 
    } 
    return result; 
} 

調用與SumStr("t5ds5")功能給出了10

預期的結果

您的代碼沒有前進str因此您檢查了每次循環都有相同的字符。它也每次調用strlen()這個循環使得算法O(n^2)不理想。根據上面的代碼,你可能會走一次字符串。

至於爲什麼你的代碼產生的訪問衝突必須是由於你沒有顯示的代碼部分。人們只能想象str必須指向一個無效的內存地址或不是空終止。

+0

不工作的傢伙,我寫我的更新代碼.. – Wl7a 2011-05-14 18:33:09

+0

@ Wl7a對不起,我錯誤地增加了循環內的str。它現在有效。 – 2011-05-14 18:34:57

+0

仍然不工作): – Wl7a 2011-05-14 19:15:23