2016-03-01 24 views
0
#include <stdio.h> 

int elofordul(int sz, int szj) { 
    int count = 0; 
    while (sz > 0) { 
     int szj2 = szj % 10; 
     sz = sz/10; 
     if (szj2 == szj) 
      count++; 
    } 
    return count; 
} 

int main() { 
    int szam, szj; 
    scanf("%d", &szam); 
    scanf("%d", &szj); 
    printf("%d", elofordul(szam, szj)); 
    return 0; 
} 

我無法弄清楚它有什麼問題。它只是打印所有的數字。 sz:數量,szj:數字數字中的特定位數

+8

難道不該'szj2 = SZ%10'? (從變量名稱不太清楚,但我想你要計算'sz'中數字'szj'出現的頻率,請嘗試選擇唯一的變量名稱匈牙利語或其他名稱,空格也有助於使代碼更具可讀性)。 –

+0

什麼是輸入和預期輸出? – Michi

+0

@Meehm就是這樣,謝謝! –

回答

1

您的功能一個錯字:szj2 = szj % 10應該szj2 = sz % 10

您應該使用英文名稱作爲變量和函數名稱,並使用英語評論。你的變量名稱很混亂,確實引起了混淆。

你的版本還有另一個潛在的錯誤:程序應該輸入1輸入0 0

下面是修改後的版本:

#include <stdio.h> 

int count_digit(int number, int digit) { 
    int count = 0; 
    for (;;) { 
     if (number % 10 == digit) 
      count++; 
     number /= 10; 
     if (number == 0) 
      return count; 
    } 
} 

int main() { 
    int number, digit; 
    scanf("%d", &number); 
    scanf("%d", &digit); 
    printf("%d", count_digit(number, digit)); 
    return 0; 
} 
+0

爲什麼他應該覺得有義務用英語發表評論? – nicomp

+3

@nicomp:用於與全球程序員進行互操作,特別是在stackoverflow上。我也不是英國人,但我爲自己的球隊執行這條規則。另一方面,C關鍵字是英文單詞,將它們與當地語言混合在一起會讓人覺得尷尬。 – chqrlie

+0

你可能是指'if((number/= 10)== 0)'。也許你可以寫循環爲'do {...} while(number/= 10);'如果它不太模糊。 –