c++ 通过递归计算整数的位数

uwopmtnx  于 2023-05-02  发布在  其他
关注(0)|答案(9)|浏览(126)

我的代码如下:
/计算整数中的位数

#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)'的参数太少,这是什么问题?

rsaldnfx

rsaldnfx1#

因为你声明了函数接受两个参数:

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;
}

并且here是工作示例。

cu6pst1q

cu6pst1q2#

int x=countNum();调用函数应该将实际参数传递给调用函数。你已经定义了函数countNum(int, int),这意味着它将从调用函数接收两个int作为参数,所以调用者应该传递它们,这在你的例子中是缺失的。这是错误的原因太少的参数。

2izufjch

2izufjch3#

您的代码:

int x=countNum();

countNum需要用两个整数调用。例如

int x=countNum(n, d);
disho6za

disho6za4#

因为您还没有向countNum函数传递参数。像int x=countNum(n,d);一样使用它

yshpjwxd

yshpjwxd5#

假设这不是一个任务,有更好的方法来做到这一点(只是几个例子):

转换为字符串

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

循环

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);
}

注意:打开尾端递归优化后,编译器会将其转换为一个循环,防止调用堆栈出现不必要的溢出。

xyhw6mcr

xyhw6mcr6#

将其更改为:

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!
}
c9qzyr3d

c9qzyr3d7#

#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;
}
9rygscc1

9rygscc18#

试试这个!在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 in Reecurssion !)
        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;
}
yzuktlbb

yzuktlbb9#

您的函数写得不正确。例如,不清楚为什么它有两个参数,也不清楚它在哪里递归地调用自己。
我会这样写

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

或者更好的定义是

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

相关问题