1172 - C语言6.20
时间限制 : 1 秒
内存限制 : 32 MB
用迭代法求
。求平方根的迭代公式为:
<img src="http://tk.hustoj.com:80/upload/pimg1209_2.gif" width="118" height="49" align="middle" alt="" />
当前后两次迭代求出的x的差的绝对值小于10<sup>-5</sup>时就能够得出解。
题目输入
一个正实数a。
题目输出
输出迭代法求出的a的平方根,保留4位小数。
请注意行尾输出换行。
输入/输出样例
输入格式
12
输出格式
3.4641
C语言解答
#include<stdio.h> #include<math.h> int main(){ float a,x1,x2; scanf("%f",&a); x2=a; while(fabs(x1-x2)>1e-5){ x1=x2; x2=(x1+a/x1)/2.0; } printf("%.4f\n",x1); return 0; }
C++解答
#include <stdio.h> #include <math.h> int main() { float a, x, newx; scanf("%f", &a); newx = a; do { x = newx; newx = 0.5 * (x + a / x); } while (fabs(x - newx) >= 1e-5); printf("%.4f\n", x); return 0; }
Java解答
import java.util.*; public class Main { public static void main(String args[]) { Scanner cin=new Scanner(System.in); int a=cin.nextInt(); double x; x=a/2; while(Math.abs(x-(x+a/x)/2)>0.00001) x=(x+a/x)/2; System.out.printf("%.4f\n", x); } }
Python解答
def f(a, x): y = (x + a / x) / 2.0 return y if 10**-5 > y - x > -10**-5 else f(a, y) print "%.4f" % (f(input(), 1))