伙计们,我有一个问题,要创建一个函数来计算整数中一个数字的出现。我创建了2 int,int n,其中包含0到9之间的值,其中int值是一个数字,最多可达9位数。我必须创建一个函数countOccurence来计算每个数字在我输入的值中发生了多少次。例如,如果我输入"12345",则1 2 3 4 5发生一次,而6 7 8 9 0发生0次。我试过了但被卡住了。
这就是我到目前为止所得出的结论,我只是想不出答案。
#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)
{
}谢谢你的帮助,我真的很感激
发布于 2015-02-22 04:43:26
这样的东西应该能给你你想要的东西。
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);
}编辑
如果您需要countOccourence来返回一个值,就应该这样做。
int countOccourence(int dig, int val)
{
if(n > 0)
{
return countOccourence(dig, val / 10) + (val % 10 == dig);
}
else
return 0;
}https://stackoverflow.com/questions/28654545
复制相似问题