首页 > 试题广场 >

用迭代法求。求平方根的选代公式为 要求前后两次

[问答题]

用迭代法求求平方根的选代公式为

要求前后两次求出的x的差的绝对值小于10^-5


推荐

#include<stdio.h>

#indude<math.h>

int main( )

{

float a,x0,x1;

printf("enter a positive number.");

scanf("%f",&a);

x0=a/2;

x1=(x0+a/x0)/2;

do

{ x0=x1;

x1=(x0+a/x0)/2;

}while(fabs(x0-x1>=1e-5);

printf("The square root of %5.2f is %8.5f\n",a,x1);

return 0;

}


发表于 2018-03-25 10:57:35 回复(0)
#include <stdio.h>
//导入"math.h"头文件
#include "math.h"

int main() {

    //pow()函数用来求x的y次方的值
    //sqrt()函数求出原数值的开根号后的结果
    float x1,x2,a;
    float s = 0;
    printf("请输入一个数字a:");
    scanf("%f",&a);
    x1 = sqrt(a);
    x2 = (x1+a/x1)/2;
    while(fabs(x1-x2) >= 1e-5){
        x1 = x2;
        x2 = (x1+a/x1)/2;
    }
    printf("此时的a是%5.2f,x2是%5.2f",a,x2);
    return 0;
}

发表于 2022-10-03 17:35:02 回复(0)
#include<stdio.h>
#include<math.h>
int main(){
	float x,a,x1;
	printf("请输入:a=");
	scanf("%f",&a);
	x=a;
	do{
		x1=x;
		x=(x1+a/x1)/2;	//迭代公式 
	}while(fabs(x-x1)>=1e-5);
	printf("a的算术平方根=%f",x);	//题目所求为算术平方根,故只取正值 
	return 0;
}

发表于 2021-01-17 17:28:43 回复(0)
def square_root(n:int)->float:
    """ f(x) = x^2 - n = 0,求该方程的根
    """
    x0 = 1
    for i in range(100):
        x1 = x0 - (x0**2 - n)/(2*x0)
        if x1 - x0 < 1e-20 and x1-x0> -1e-20:
            print("total iterations: ", i+1)
            break
        

        x0 = x1
    
    return x1

发表于 2020-04-30 13:32:59 回复(0)
#include <stdio.h>
double power(int x , int n){
 if(n < 0){
  double k = 1;
  for(int i = 0; i > n; i --){
   k /= (double)(x);
  }
  return k;
 }
}
double sgn(double s){
 if(s > 0)
  return  s;
 else
  return -1 * s;
}
double Sqrt(double n){//开根号函数可以通过迭代实现,x0 = n, xn = 1.0/2.0 * (xn-1 + (n / xn-1))
 double store[10000];
 for(int i = 0; i < 10000; i ++){
  store[i] = 0;
 }
 store[0] = n;
 int t = 0;
 for(int i = 1; ;i ++){//考察类型转换,1 / 2分子分母都是整型变量,保留结果是0
  store[i] = (store[i - 1] + (n / store[i - 1])) / 2;//想要实现乘以分数,要对分子分母进行类型转化成浮点数类型,
  t ++;
  if(sgn(store[i] - store[i - 1]) < power(10, -5))
      break;
 }
 return store[t];
}
int main(){
    double n;
    scanf("%lf", &n);
    printf("%lf\n", Sqrt(n));
}
发表于 2019-12-23 22:54:00 回复(0)