用c++求一个实数x的y次方根(y为正整数且当y为偶数时,x≥0)

这次将上次发的平方根算法改进了一下,代码更简明,
还做了一个求实数x的y次方根(y为正整数,且当y为偶数时,x≥0)的算法
改进后的平方根算法:
#include < iostream>
using namespace std;
double a,ans;
bool check(double a,double b)
{
double eps=0.0001;
if(a>b)
{
if(a-b>eps)
{
return false;
}
return true;
}
else
{
if(b-a>eps)
{
return false;
}
return true;
}
}
void sqareroot(double n)
{
while(ansans<=a)
{
ans+=n;
}
ans-=n;
if(!check(ans
ans,a))
{
sqareroot(n/10);
}
}
int main()
{
cin>>a;
sqareroot(1000000);//这里n的值要形为10的x次方(x为≥0的整数),越大就越快,不必担心会变慢,因为例如这里n为100万,
即使整数位为1也只需要log10 1000000=7次计算,这是为了防止被开方的数太大而导致过慢。
cout<<ans;
return 0;
}
接下来就是求一个实数x的y次方根的算法了
#include <bits/stdc++.h>
using namespace std;
double a,ans;
int k;
bool check(double a,double b)
{
double eps=0.0000001;
if(a>b)
{
if(a-b>eps)
{
return false;
}
return true;
}
else
{
if(b-a>eps)
{
return false;
}
return true;
}
}
void root(int x,double n)
{
while(pow(ans,x)<=a)
{
ans+=n;
}
ans-=n;
if(!check(pow(ans,x),a))
{
root(x,n/10);
}
}
int main()
{
cin>>a>>k;
root(k,1000000);
cout<<ans;
return 0;
}//原理基本同上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值