上次那个算上次那个算法其实已经很不错了,但我还发现了一个更快的。
主要是因为对于大于一万亿的数比较慢,现在又用二分算法对上次的递归进行了优化
#include <bits/stdc++.h>
using namespace std;
double binarySearch(double x,int y,double low,double high)//二分查找算法
{
double mid=(low+high)/2;
double guess=pow(mid,y);
if(abs(guess-x)<0.00001)
{
return mid;
}
else if(guess<x)
{
return binarySearch(x,y,mid,high);
}
else
{
return binarySearch(x,y,low,mid);
}
}
double Root(double x,int y)
{
if(x0)
{
return 0;
}
else if(x<0 && y%20)
{
return 0;
}
else
{
double low,high;
if (x < 1)
{
low=x;
high=1;
}
else
{
low=1;
high=x;
}
return binarySearch(x,y,low,high);
}
}
int main()
{
double x;
int y;
cin >> x;
cin >> y;
double root=Root(x, y);
cout<<fixed<<setprecision(5)<<root;//这里主要是为了防止得数太大而被转化成用科学计数法表示(这样不直观)
return 0;
}
用c++求一个实数x的y次方根(进阶版)
最新推荐文章于 2024-07-19 23:11:36 发布