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

标签 c++

我有我的代码。这是关于递归的。我必须创建函数 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/

相关文章:

c++ - 在线托管帮助内容

c++ - 将文件嵌入iOS应用(C++/Qt/cmake)

c# - C# 代码和非托管 C++ 库之间的双向通信

c++ - 获取 QuickFix::Field::OrdType 的值?

java - 使用 OpenSSL 的多个连接

c++ - 如何制作一个不刷新 std::cout 的简单 C++ 程序

c++ - 在 Qt 中实现回调

c++ - 在多次调用的函数中声明指针

c++ - 如何打印数组中的回文数和质数

NetBeans 中的 C++ 显示错误(无法解析标识符)但代码运行正常