第14题:在我的电脑上能够运行,因为double是有精度限制的,当A=103时,运行10次就会停止了。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
double A=103;
double x=1.0;
double newx=0;
int i=0;
while(1)
{
cout<<++i<<endl;
newx=0.5*(x+A/x);
if(newx==x)
{
cout<<x<<endl;
break;
}
x=newx;
}
system("pause");
return 0;
}
第17题:
看到结果我是彻底给跪了,我还以为程序写错了,然后把两个结果比较了一下,就是那个0.0000001的门限,结果是没有错误。不知道C++里是怎么写的sprt,根本不像是《编程珠玑》里写的,库函数已经特别快了,或许是因为《编程珠玑》毕竟是在上世纪80年代写的书,库函数已经被优化了30多年了吧。如下是代码和结果:
#include<iostream>
#include<ctime>
using namespace std;
double distanceEuclid(double p,double q)
{
p=abs(p);
q=abs(q);
if(p<q)
swap(p,q);
if(p==0.0)
return q;
int n=3;
double r;
while(n--)
{
r=q/p;
r=r*r;
r=r/(4+r);
p=p+2*r*p;
q=q*r;
}
return p;
}
int main()
{
const int N=10000000;
int *A=new int[N];
clock_t start,end;
srand(12345);
start=clock();
for(int i=0;i<N;i++)
{
double a=rand();
double b=rand();
A[i]=distanceEuclid(a,b);
}
end=clock();
cout<<end-start<<endl;
srand(12345);
start=clock();
for(int i=0;i<N;i++)
{
double a=rand();
double b=rand();
if(A[i]-sqrt(a*a+b*b)>0.0000001)
cout<<"error"<<endl;
}
end=clock();
cout<<end-start<<endl;
system("pause");
return 0;
}
结果: