需要一个代码,计数相同的数字在一个数字
Need a code that counts the same digit in a number
正如标题所说,需要一个代码来计算数字中的相同数字…
例如:如果我输入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));
您可以将号码作为字符串输入,然后解析该字符串
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 以C++输出一个数字三角形
- 反转一个数字程序不起作用,为什么?
- 如何让用户在 c++ 中选择一个数字
- 输出一个数字,该数字可能是三种类型之一
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- C++[递归]将一个数字写成2的升序之和
- 试图找到一个数字的平方根,但代码不起作用。C++
- 我没有得到一个数字作为输出,而是一个表情符号
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 你怎么编码,如果x不等于一个数字,程序就会退出
- 如何将整数数组相乘得到一个数字?
- 为无符号字符* 分配一个数字
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 字符串和双精度的麻烦,等值后再得到一个数字