需要一个代码,计数相同的数字在一个数字

Need a code that counts the same digit in a number

本文关键字:一个 数字 代码      更新时间:2023-10-16

正如标题所说,需要一个代码来计算数字中的相同数字…

例如:

如果我输入54678,它会显示数字5在这个整数中出现的次数。

12341 -- You used number 1 two times
88888 -- You used number 8 five times

谢谢你的帮助,我还在学习c++

编辑:

#include <iostream>
using namespace std;
int getNumber ()
{
int x;
cout << "Enter a long number: ";
cin >> x;
return x;
}
int getDigit ()
{
int y;
cout << "Enter a single digit (0-9): ";
cin >> y;
return y;
}
int digitCounter ( int x, int y )
{
if ( x < 10 )
{
if ( x == y )
return 1;
return 0;
}
return digitCounter (x%10, y) + digitCounter (x/10, y);
} 

int main()
{
int number = getNumber();
int digit = getDigit();
int count = digitCounter( number, digit );
cout<< "The digit " << digit << " appeared " << count << " time";
if ( count != 1 )
cout << "s";
cout << "." <<endl;
return 0;
} 

您可以使用这样的函数,其中n是数字,d是要计数的数字:

int count_dig(int n, int d) {
    int result = 0;
    while (n > 0) {
        if (n % 10 == d) {
            result++;
        }
        n/=10;
    }
    return result;
}

使用这个,您可以打印格式化的结果,如:

printf("%d -- You used digit %d %d times.", n, d, count_dig(n, d));

您可以将号码作为字符串输入,然后解析该字符串