与神明说


私信TA

用户名:subject

访问量:32143

签 名:

听闻黄昏是个浪漫主义者,难怪夕阳会爱上他

等  级
排  名 376
经  验 5019
参赛次数 0
文章发表 33
年  龄 24
在职情况 在职
学  校
专  业 软件技术

  自我简介:

可有偿指导,可代做毕设,课设,作业,(qq:1159921160,备注来意)

解题思路:

牛顿迭代法求平方根:
    假设a。欲求a的平方根,首先猜测一个值X1=a/2,然后根据迭代公式 X(n+1)=(Xn+a/Xn)/2,
    算出X2,再将X2代公式的右边算出X3等等,直到连续两次算出的Xn和X(n+1)的差的绝对值小于
    某个值,即认为找到了精确的平方根
    
例:
假设a=4,
    x1=4/2=2; 
    x2=(2+4/2)/2=2   2-2<0.00001
    ==>平方根=2
    
假设a=9,
    x1=9/2=4.5; 
    x2=(4.5+9/4.5)/2=3.25   4.5-3.25>0.00001
    x3=(3.25+9/3.25)/2=3.00962   3.25-3.00962>0.00001
    x4=(3.00962+9/3.00962)/2=3.00002   3.00962-3.00002>0.00001
    ....
     ==>平方根=3
     
     利用循环,即可解题


注意事项:

    理解题意,善用循环,绝对值得差小于0.00001


参考代码:

#include"iostream" 
#include"cmath"     //调用求绝对值函数  fabs();
#include"cstdio"    //使用格式化输出printf();
using namespace std;

int main(){
	double x,b,c;
	cin>>x;
	b=x/2;
	while(1){
		c=(b+x/b)/2;
		if(fabs(c-b)<0.00001)
			break;
		b=c;
	}
	printf("%.3lf\n",c);
	return 0;
}


 

0.0分

60 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

那个,我想问一下初始值为什么是a/2?这个值是看你要求的数的平方根是什么然后按情况设的嘛?
2022-07-24 08:29:51
我都理解不了题目!。。。
2022-06-01 18:56:04
为什么我的值 -0.000
2021-05-13 15:15:19
//输出n的所有因子
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	double N ;
	double a , b ; 
	cin>>N ; //16
	
	a = N / 2 ; //8
	b = ( a + (N/a) ) / 2 ; // 8+2 / 2 = 5 ;

	while((a-b)>0.00001)
	{
		//a - b > 0.00001
		a = b ;
		
		b = ( b + N/b ) / 2 ;
		
	}
	
	cout<<fixed<<setprecision(3)<<b;
	

    return 0;
}
2021-04-22 20:25:01
#include<bits/stdc++.h>
#include<cmath>
using namespace std;
   int main(){
   	double a,b,c;
   	cin >>a;
   	b=a/2;
   	while (1){
   		c=(b+a/b)/2;
   		if(fabs(c-b)<0.00001)
   		break;
   		b=c;
	   }
	cout <<fixed<<setprecision(3)<<c<<endl;
	   
   	return 0;
   }
2021-02-17 18:02:46
很棒,对迭代法做了一个详细的说明,比光有代码的好多了,赞
2021-02-02 10:55:10
#include<stdio.h>
int main()
{
	float s,a;
	scanf("%f",&a);
	s=a/2.0;
	while(1){
		if((s+a/s)/2.0-s<0.00001){
		printf("%0.3f\n",(s+a/s)/2.0);break;
		}
	s=(s+a/s)/2.0;
	}

return 0;
}
2020-03-06 19:55:00
为什么
fabs(b-a)<0.00001  必须要在if里
while(fabs(b-a)>0.00001)  为什么会错?
2020-02-28 12:52:35