需要一个可以计算数字中相同数字的代码 [英] Need a code that counts the same digit in a number
本文介绍了需要一个可以计算数字中相同数字的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所说,需要一个在数字中计算相同数字的代码.
As title says , need a code that counts the same digit in a number..
例如:
如果我输入54678,它会告诉我该整数中使用了多少个数字5.
If I put 54678, it shows me how many number 5 is used in that integer.
12341 -- You used number 1 two times
88888 -- You used number 8 five times
谢谢您的帮助,我仍在学习c ++
Thank you for any help, I'm still learning 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是您要计数的数字:
You could use a function like this, where n is the number and d is the digit you want to count:
int count_dig(int n, int d) {
int result = 0;
while (n > 0) {
if (n % 10 == d) {
result++;
}
n/=10;
}
return result;
}
使用此方法,您可以打印格式化的结果,例如:
Using this, you could print your formatted result like:
printf("%d -- You used digit %d %d times.", n, d, count_dig(n, d));
这篇关于需要一个可以计算数字中相同数字的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文