用c++求一个实数x的y次方根(进阶版)

上次那个算上次那个算法其实已经很不错了,但我还发现了一个更快的。
主要是因为对于大于一万亿的数比较慢,现在又用二分算法对上次的递归进行了优化
#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%2
0)
{
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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值