我需要有关如何求某个数字的 n 次方根的帮助。
用户输入数字 n 和他想要根的数字。我需要在没有 cmath lib 的情况下使用分而治之的方法来解决这个问题。
这是我的代码,目前还无法运行:
#include<iostream>
using namespace std;
float pow(float a,float c){
if (a == 0)
return 0;
else if(a == 1)
return 1;
else{
float p = pow(a,(c/2));
if(c%2)
return p*p*a;
else
return p*p;
}
}
int main(){
float a,b;
float c;
cout << "Enter positive number:(base)" << endl;
do{
cin >> a;
}while (a < 0);
cout << "Enter number: (root)" << endl;
cin >> b;
c = 1/b;
cout << "Result:"<<pow(a,c) << endl;
system("pause");
return 0;
}
关于如何解决这个问题的任何想法都将非常有用。
让我告诉您如何使用分治法来求平方根。 n 次方根也类似。
对于给定的数字x
,你需要搜索它的平方根0
and x
。将其除以2
= x2
。如果x2 * x2
< x
然后你的搜索空间移动到x2 -> x
否则将会是0 -> x2
. If x2 * x2
火柴x
那么你的平方根是x2
。 n 次方根的类似技术。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)