2015-10-19 64 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

相关问题