2015-10-19 67 views
0

我正在嘗試編寫一個程序來計算一個數字中的5的數量並顯示它。因此,如果用戶輸入:找到一個數字中的特定重複數字

52315 

然後程序應該ouptut:

Yes, there are '5's and they're 2 

這裏是我的代碼,但有一些毛病。

{ 
    int n,m; 
    int count = 0; 
    cout << "Enter an: "; 
    cin >> n; 

    int *arr; 
    arr = new int[count]; 

    // Getting digits from number 
    while (n > 0) 
    { 
     count++; 
     m = n%10; 
     n = n/10; 

    //Trying to put every digit in an array 

     for (int i = 0; i<count; i++) 
     { 
      cin>>arr[i]; 
      arr[i] = m; 
      cout << arr[i]; 
     } 
     int even = 5; 
    //Trying to see if there's a digit 5 in inputed number and how many if so. 
     for (int j = 0; j<count; j++) 
     { 
      if (arr[j]==even) 
      { 
       cout << "Yes, there's a digit '5' " << endl; 
       s++; 
      } 
     } 



     cout << "Count of '5's : " << even; 
     delete[] arr; 
    } 



    return 0; 
} 
+3

首先,什麼是非常錯誤的?你必須精確地解釋什麼是預期產出(你這樣做了),而且你得到的實際產出是多少。我猜測你的數組的創建首先不是很好。 – LBes

+1

您希望將'%'運算符與'/'結合使用,並且實際上並不需要該數組。 (並且調用5「even」有點奇怪。) – molbdnilo

+0

@molbdnilo更改了代碼lil bit,你能看出現在有什麼問題嗎? – Maartin1996

回答

1

for (int i = 0; i<count; i++) 
{ 
    cin >> arr[i]; 
} 

你試圖填充其它用戶輸入,而不是現有的一個數組。

你也可以不用數組:

int count = 0; 
int n; 
cin >> n; 

do { 
    if (n%10 ==5) count++; 
    n /= 10; 
} while (n); 

cout << "Count of '5's : " << count; 
+0

沒有錯誤,但是當我輸入151時,沒有任何反應。 – Maartin1996

+0

可以和我一起工作:http://ideone.com/0tnTYL –

0

這應該爲每個號碼做到這一點。 如果你只想知道一個像5這樣的特殊數字,只需刪除for循環並打印計數[theNumberYouWantToKnow]。

#define BASE 10 

void output() { 
    int givenNumber; 

    cout << "Please enter a number: "; 
    cin >> givenNumber; 

    int count[BASE] = { 0 }; 

    while(givenNumber > 0) { 
     int digit = givenNumber % BASE; 
     givenNumber /= BASE; 
     count[digit]++; 
    } 

    for(int i = 0; i < BASE; i++) { 
     cout << "Found the number " << i << " " << count[i] << " times." << endl; 
    } 
} 
+0

'base'可以是一個常量,所以'count'可以是一個數組。 – user666412

相關問題