Raj*_*tel 6 c++ pass-by-reference
使用递归函数myPowerFunction(int p,int n,int和currentCallNumber)计算P的n次幂(p和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);
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ker 10
您需要一个变量作为main_program中的第三个参数传递.您不能将常量作为非const引用传递.
int count = 0;
std::cout << myPowerFunction(3, 4, count) << 'n';
std::cout << count << '\n';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10917 次 |
| 最近记录: |