编写递归函数GetPower(int x,int y) 计算X的Y次幂,在主程序中实现输入输出。

2024-11-17 14:02:25
推荐回答(4个)
回答1:

float GetPower(int x, int y)
{
if(y==0) return 1;
else
{
if(y>0) return (float)(GetPower(y-1)*x);
else return (float)(GetPower(y+1)/x);

}
}
void main()
{
int x,y;
printf("Input x^y:\n");
scanf("%d%d",&x,&y);
pinrtf("\n%d^%d=%0.0f",x,y,GetPower(x,y));
}

回答2:

int GetPower(int x,int y)
{
if (y==1) return x;
return x* GetPower( x, y-1) ;
}

回答3:

int GetPower(int x,int y)
{
if(y==0)return 1;
else return x*GetPower(x,y-1);
}

回答4:

这个是整个求x^y的值的程序,这里包含了getPower的函数定义。
#include
using namespace std;
int getPower(int x, int y);
double getPower(double x, int y);
int main()
{
int iNumber, power;
double dNumber;
int iAnswer;
double dAnswer;
cout << "Enter an int base number:";
cin >> iNumber;
cout << "Enter an double base number:";
cin >> dNumber;
cout << "To what power?";
cin >> power;
iAnswer = getPower(iNumber, power);
dAnswer = getPower(dNumber, power);
cout << iNumber << "to the " << power << "th power is " << iAnswer << endl;
cout << dNumber << "to the " << power << "th power is " << dAnswer << endl;
return 0;
}
int getPower(int x, int y)
{
if (y == 1)
return x;
else if (y == 0)
return 1;
else if (y < 0)
return 1 / getPower(x, -y);
else
return (x*getPower(x, y-1));
}
double getPower(double x, int y)
{
if (y == 1)
return x;
else if (y == 0)
return 1;
else if (y < 0)
return 1 / getPower(x, -y);
else
return (x*getPower(x, y-1));
}