通过递归计数整数中的数字数量

Counting number of digits in an integer through recursion

本文关键字:数字 整数 递归      更新时间:2023-10-16

我的代码如下:

/整数中的数字数

#include <iostream>
using namespace std;
int countNum(int n,int d){
    if(n==0)
    return d;
    else
    return (n/10,d++);
}
int main(){
    int n;
    int d;
    cout<<"Enter number"<<endl;
    cin>>n;
   int x=countNum();
    cout<<x;
    return 0;
}

我无法弄清楚错误,它说:很少有参数来起作用`int countnum(int,int)'什么是问题?

,因为您声明了函数进行两个参数:

int countNum(int n,int d){

您没有传递:

int x = countNum();

您可能打算这样称呼它,而是:

int x = countNum(n, d);

另外:

return (n/10,d++);

应该是这样的:

return countNum(n/10,d++);

您也不初始化nd变量:

int n;
int d;

最后,您根本不需要d参数。这是一个更好的版本:

int countNum(int n){
    return (n >= 10)
        ? 1 + countNum(n/10)
        : 1;
}

这是工作示例。

int x=countNum();呼叫者函数应将实际参数传递给调用函数。您已经定义了countNum(int, int)的函数,这意味着它将接收两个INT作为来自调用函数的参数,因此呼叫者应将其传递给它们,而它们在您的情况下丢失了。这就是错误的原因太少。

您的代码在这里:

int x=countNum();

countnum需要与两个整数一起调用。例如

int x=countNum(n, d);

,因为您尚未将参数传递给countNum函数。像int x=countNum(n,d);

一样使用它

假设这不是为了分配,有更好的方法可以做到这一点(只有几个示例):

转换为字符串

unsigned int count_digits(unsigned int n)
{
    std::string sValue = std::to_string(n);
    return sValue.length();
}

loop

unsigned int count_digits(unsigned int n)
{
    unsigned int cnt = 1;
    if (n > 0)
    {
        for (n = n/10; n > 0; n /= 10, ++cnt);
    }
    return cnt;
}

尾部末端递归

unsigned int count_digits(unsigned int n, unsigned int cnt = 1)
{
    if (n < 10)
        return cnt;
    else
        return count_digits(n / 10, cnt + 1);
}

注意:随着尾端递归优化的打开,您的编译器将为您转换为循环 - 防止呼叫堆栈的不必要的洪水。

将其更改为:

int x=countNum(n,0);

您不需要通过d,您只需将0作为种子传递。

还将countNum更改为:

int countNum(int n,int d){
    if(n==0)
    return d;
    else
    return coutNum(n/10,d+1); // NOTE: This is the recursive bit!
}
#include <iostream>
using namespace std;
int countNum(int n,int d){
    if(n<10)
        return d;
    else
        return countNum(n/10, d+1);
}
int main(){
    int n;
    cout<<"Enter number"<<endl;
    cin>>n;
    int x=countNum(n, 1);
    cout<<x;
    return 0;
}

YouTube上的PMI(数学归纳原则)。它使递归非常容易。尝试以下操作:

#include<iostream>
using namespace std;
    
int count(int n){
    //Base Case
    if(n == 0){
        return 0;
    }
    // Recursive Step
    // We don't have to worry about the smaller steps.
    // Don't go deep into the recursion!
    int smallerInput  = count(n/10);
    
    //Calculation Step
    return smallerInput + 1;
}   
int main()
{   
    int num;
    cout << "Enter the number: ";
    cin >> num;
    
    cout << "The number of digits are : " << count(num) << endl;
    return 0;
}

您的功能编写不正确。例如,尚不清楚它为什么有两个参数或递归召集的位置。

我会以以下方式写下

int countNum( int n )
{
   return 1 + ( ( n /= 10 ) ? countNum( n ) : 0 );
}

,甚至最好将其定义为

constexpr int countNum( int n )
{
   return 1 + ( ( n / 10 ) ? countNum( n/10 ) : 0 );
}