这次将上次发的平方根算法改进了一下,代码更简明,
还做了一个求实数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(ansans,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;
}//原理基本同上
用c++求一个实数x的y次方根(y为正整数且当y为偶数时,x≥0)
于 2023-08-16 20:47:00 首次发布