候选函数不可行:期望第三个参数的l值。

时间:2021-11-13 19:30:58

Calculate nth power of P (both p and n are positive integer) using a recursive function myPowerFunction(int p, int n, int &currentCallNumber). currentCallNumber is a reference parameter and stores the number of function calls made so far. myPowerFunction returns the nth power of p.

用递归函数myPowerFunction(int P, int n, int &currentCallNumber)计算P (P和n都是正整数)的n次幂。currentCallNumber是一个引用参数,并存储到目前为止所调用的函数调用的数量。myPowerFunction返回p的n次幂。

int myPowerFunction(int p, int n, int &z)
{
    z++;
    if(n==1)return p;
    else if(n==0)return 1;
    else if(n%2==0)return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z);
    else return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z)*p;
}

int main()
{
    cout << myPowerFunction(3,4,1);
}

3 个解决方案

#1


10  

You need a variable to pass as the third argument in main_program. You can't pass a constant as a non-const reference.

您需要一个变量作为main_program中的第三个参数。你不能将常数作为非常量引用。

int count = 0;
std::cout << myPowerFunction(3, 4, count) << 'n';
std::cout << count << '\n';

#2


2  

Third parameter expects a lvalue, so you cannot pass numeric constant there, so possible solution can be:

第三个参数需要一个lvalue,所以不能在那里传递数值常量,所以可能的解决方案是:

int z = 1;
cout<< myPowerFunction(3,4,z);

or better to create a function that calls recursive one:

或者更好地创建一个调用递归函数的函数:

int myPowerFunction(int p, int n)
{
    int z = 1;
    return myPowerFunction(p,n,z);
}

#3


1  

In myPowerFunction(3,4,1) the literal 1 cannot be passed to a non const reference as it is a prvalue [basic.lval]. You need to store the value into a variable and then use that variable when calling the function.

在myPowerFunction(3,4,1)中,文字1不能被传递给一个非常量引用,因为它是一个prvalue [basic.lval]。您需要将该值存储到一个变量中,并在调用函数时使用该变量。

int z = 0;
std::cout << myPowerFunction(3, 4, z);

#1


10  

You need a variable to pass as the third argument in main_program. You can't pass a constant as a non-const reference.

您需要一个变量作为main_program中的第三个参数。你不能将常数作为非常量引用。

int count = 0;
std::cout << myPowerFunction(3, 4, count) << 'n';
std::cout << count << '\n';

#2


2  

Third parameter expects a lvalue, so you cannot pass numeric constant there, so possible solution can be:

第三个参数需要一个lvalue,所以不能在那里传递数值常量,所以可能的解决方案是:

int z = 1;
cout<< myPowerFunction(3,4,z);

or better to create a function that calls recursive one:

或者更好地创建一个调用递归函数的函数:

int myPowerFunction(int p, int n)
{
    int z = 1;
    return myPowerFunction(p,n,z);
}

#3


1  

In myPowerFunction(3,4,1) the literal 1 cannot be passed to a non const reference as it is a prvalue [basic.lval]. You need to store the value into a variable and then use that variable when calling the function.

在myPowerFunction(3,4,1)中,文字1不能被传递给一个非常量引用,因为它是一个prvalue [basic.lval]。您需要将该值存储到一个变量中,并在调用函数时使用该变量。

int z = 0;
std::cout << myPowerFunction(3, 4, z);