1 概述

用迭代法求 x = \sqrt{a}。求平方根的迭代公式为:x_{n+1} = \frac{1}{2}(x_{n} + \frac{a}{x_{n}})

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

2 分析

通过公式迭代求出x = \sqrt{a}的值;什么时候迭代结束呢,就是x_{n+1}x_{n}的差值小于10^{-5}时。

2.1 解法1 

// 迭代法求x等于根号下a的值
#include<stdio.h>
#include<math.h>
 
int main() {
	double x1, x2;
	float a;
	scanf("%f", &a);
	x2 = 1.0;
	for (;;) {
		x1 = x2;
		x2 = (x1 + a / x1) / 2.0;  // 迭代公式 
		if (fabs(x1 - x2) < 1e-5) {
			printf("%f", x2);
			break;
		}
	}
	return 0 ;
}

2.2 解法2

// 迭代法求x等于根号下a的值
#include<stdio.h>
#include<math.h>
 
int main() {
	double x1, x2;
	float a;
	scanf("%f", &a);
	x2 = 1.0;
	do{
		x1 = x2;
		x2 = (x1 + a / x1) / 2.0;  // 迭代公式 
	}while(fabs(x1 - x2) > 1e-5);
	printf("%f", x2);
	return 0 ;
}

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐