[英]find digits occurence in an integer
I guys I have a problem to create a function to count the occurrence of a number in my integers. 伙计们,我无法创建一个函数来计算整数中数字的出现。 I create 2 int, int n which contains value from 0 to 9. Where the int value is a number that can be 1 digit up to 9 digit.
我创建2个int,int n包含从0到9的值。其中,int值是可以是1位数到9位数的数字。 I have to create a function countOccurence to count how many times each digit occurs in the value that I put in. For example, if I type "12345", then 1 2 3 4 5 occurs once, while 6 7 8 9 0 occurs zero times.
我必须创建一个函数countOccurence来计算我输入的值中每个数字出现多少次。例如,如果我键入“ 12345”,则1 2 3 4 5出现一次,而6 7 8 9 0出现零。次。 I try it but I just got stuck.
我尝试过,但是我被卡住了。
Here is what I come up so far, I just cant figure it out. 这是我到目前为止提出的内容,我只是无法弄清楚。
#include <iostream>
using namespace std;
int main()
{
int countOccurance(int, int);
int findDig(int);
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 999999999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
}
//process the value
}
int countOccurance(int findDig, int value)
{
}
thank you for your help, I really appreciate it 谢谢您的帮助,我非常感谢
Something along these lines should give you what you're looking for. 这些思路可以为您提供所需的东西。
int findDig(int n)
{
if (n < 10)
return 1;
else
return 1 + findDig(n / 10);
}
int countOccurance(int value)
{
for(int i = 0 ; i < 10 ; i++)
{
int val = value;
int count = 0;
while(val > 0)
{
if(val % 10 == i)
count ++;
val /= 10;
}
cout << count << " occourences of " << i << endl;
}
}
int main()
{
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 999999999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
cin >> value //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
}
//process the value
cout << endl;
cout << "This " << value << " number is a " << findDig(value) << " digit integer number." << endl;
cout << "Digit counts" << endl;
countOccourance(value);
}
edit 编辑
If you need countOccourence to return a value, this should do it. 如果您需要countOccourence返回一个值,则应该这样做。
int countOccourence(int dig, int val)
{
if(n > 0)
{
return countOccourence(dig, val / 10) + (val % 10 == dig);
}
else
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.