查找数字中特定的重复数字

Finding specific repeated digits in a number

本文关键字:数字 查找      更新时间:2023-10-16

我正在尝试编写一个程序,该程序将计算数字中5 s的数量并显示它。所以如果用户输入:

52315

程序应该输出:

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;
}

This

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;

对于每个数字都应该这样做。如果你只想知道一个特殊的数字,比如5,只需删除for循环并打印count[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;
    }
}