python:
#coding=utf-8 from decimal import Decimal from decimal import getcontext #设置为显示8位有效数字 getcontext().prec=8 #求6的平方根 x=6 x=Decimal(str(x)) a=x/Decimal("2") diff=0 while(1): b = (a + x / a) / Decimal("2") diff=a-b a=b if(diff < Decimal("0.001")): break print(a)
输出
2.4494898
c:
#include<stdio.h> int main(){ //求6的平方根 int x=6; float a=x/2.0; float diff=0.0; float b=0.0; while(1){ b=(a+x/a)/2.0; diff=a-b; a=b; if(diff<0.001){ break; } } printf("平方根为%f\n",a); return 0; }
输出
平方根为2.449490
参考:
https://www.jianshu.com/p/b31f078994f0
https://blog.csdn.net/qq_16676375/article/details/82909145
https://jingyan.baidu.com/article/f79b7cb31082079144023ebb.html