用迭代算法求非负数num的平方根。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wo_aisilebiancheng/article/details/50783330
 
 
/*
用迭代算法求非负数num的平方根。
迭代公式为:temp_2 = (temp_1 + num / temp_1) / 2;
(库函数sqrt()已经实现)
*/
#include <stdio.h>
#include <math.h>
int main() {

	float num = 0, temp_1 = 0, temp_2 = 0;
	printf("请输入一个正数:\n");
	scanf("%f", &num);
	if(num < 0) {
		printf("输入的num为负数!!!!\n");
		return 0;
	}else {

		temp_1 = num / 2;
		temp_2 = (temp_1 + num / temp_1) / 2;
		// 对于浮点数来说当两者之差小与1e-5时,表示两个数相等
		while(fabs(temp_1 - temp_2) > 1e-5){

			temp_1 = temp_2;
			temp_2 = (temp_1 + num / temp_1) / 2;
		}
		printf("sqrt(%f) = %f\n", num, temp_1);
		return 0;
	}
}


猜你喜欢

转载自blog.csdn.net/wo_aisilebiancheng/article/details/50783330
今日推荐