注册 登录
编程论坛 C++教室

用递归写了个求x 的n次幂的函数,结果错了,求指教

好笨的鸟 发布于 2013-04-05 15:07, 1066 次点击
代码如下,运行结果老是出错求指教
#include<iostream>
int main()
{
    using namespace std;
    //求x 的n次幂
    double x,n,y;
    y = 1;
    int z = 0;
    double xn(double x,double n,double y,int z);
    cout<<"请输入 x 和 n : ";
    cin >> x >> n;
    cout << endl
          << "x 的 n 次幂为 :"
          << xn(x,n,y,z);
}
double xn (double x,double n,double y,int z)
{
    if ( z = 0 )                    //定义了z 在第一轮判断 n >0 or n ==0 or n < 0
    {
        z = 1;
        if ( n > 0 )
            xn (x,n,y,z);
        if ( n == 0 )
            if ( x == 0 ) return 0;
            else return 1;
        if ( n < 0 )
        {    n = -n;
            xn (1/x,n,y,z);
        }
    }
    else
    {
        y *= x;
        if ( --n > 0 )
            xn(x,n,y,z);
        else return y;
    }
}
3 回复
#2
fxbszj2013-04-05 16:00
我最讨厌递归了,看得头晕
#3
邓士林2013-04-05 17:40
   if ( z = 0 )这个表达不正确吧!   if ( z == 0 )这样吧!还有就是你y=0;是一直不变的,所以根本求不出来结果,你在考虑下。这样就可以了
#include<iostream>
using namespace std;
 int main()
 {

     //求x 的n次幂
     int x,n,y=1;
     cout<<"请输入 x 和 n : ";
     cin >> x >> n;
    while(n--)
    {
        y=y*x;
    }
    cout<<y<<endl;
    return 0;
 }
 
#4
逆水寒刘2013-04-06 13:06
#include<iostream>
using namespace std;
double xn(double x,int n);//函数声明
int main()
{         
    double x;
    int   n;
    cout<<"请输入x和n(x必须大于0): ";
    cin >> x >> n;
    while(x<=0.0)
    {
        cout<<"x小于或等于0无意义。输入错误,请重新输入"<<endl;
        cin>>x;
    }
    cout<<x<<"的"<<n<<"次幂为:";
    cout<<xn(x,n);
    cout<<endl;
    return 0 ;
}
double xn(double x,int n)
{
    if(n==0||x==1)
        return 1;
    if(n>0)
        return x*xn(x,n-1);
    if(n<0)
    {    n=-n;
       x=1.0/x;
       return x*xn(x,n-1);
    }
 
} 具体错误楼上已给出,这是我修改后的
1