gpt4 book ai didi

c++ - 找到用户输入的每个 4 位数字并使用递归对其进行计数

转载 作者:太空宇宙 更新时间:2023-11-04 13:38:28 25 4
gpt4 key购买 nike

我有我的代码。这是关于递归的。我必须创建函数 digitAppear( int findDigit, int value) 其中 value 是用户输入,findDigit 是单个数字,范围从 0至 9. 该函数读取用户输入并从用户输入中返回每个数字,并计算每个数字在用户输入中出现的次数。例如,如果我输入 1234 那么输出说 1 出现 1 次,2 出现 1 次等等(我希望我的解释清楚)问题是只能运行一次并且只能返回 1 个值。

#include <iostream>

using namespace std;

int countOccurence(int, int);

int main()
{

int findDig;
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;

while ((value < 0) || (value > 9999))
{
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
for (findDig = 0; findDig < 9; findDig++)
{
cout << endl;
cout << cout << "the " << findDig << "appear in digit " << value << " is " << countOccurence(findDig, value) << " times" << endl;
}


//countOccurance(findDig, value);
//cout
}

int countOccurence(int findDig, int value)
{
int n = value;

while( n > 10 )
{
int a = n / 10; //eliminate the right most integer from the rest
int aa = n % 10; //separate the right most integer from the rest
int b = a / 10; //eliminate the second integer from the rest
int bb = a % 10; //separate the second integer from the rest
int c = b / 10; // eliminate the third integer from the rest
int cc = b % 10; //separate the third integer from the rest

for (findDig = 0; findDig < 9; findDig++)
{
int i = 0;
if (findDig == aa) // see if the findDigit value is equal to single digit of b;
{
i += 1;
} else
{
i += 0;
}
return i;

if (findDig == bb)
{
i += 1;
} else
{
i += 0;
}
return i;

if (findDig == cc)
{
i += 1;
} else
{
i += 0;
}
return il;
}
}

}

问题是我的函数 countOccurence() 似乎不正确。我想知道是否有办法做到这一点。我已经坚持了好几天,非常感谢您的意见,谢谢。

最佳答案

要使用递归,您必须以不同的方式思考问题。

考虑如何将递归合并到函数中的最简单方法是“剥离”每个数字的过程。

执行此操作的一种非常简单的方法是查看数字中的第一个/最后一个数字,对其进行计算,然后在数字的其余部分调用自身。

希望你能从那里找出代码。

关于c++ - 找到用户输入的每个 4 位数字并使用递归对其进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28714633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com