java求一个整数的平方根,不保留小数
碰到一个面试题:
public static void main(String[] args) {
// questionOne(3);
}
// 1. java求一个整数的平方根,不保留小数
public static void questionOne(int sc) {
//保留几位小数
DecimalFormat df = new DecimalFormat("0");
System.out.print(sc + "的算术平方根是:");
System.out.println(df.format(SQR(sc)));
}
public static double SQR(int a) {
double x1 = 1, x2;
//牛顿迭代公式
x2 = x1 / 2.0 + a / (2 * x1);
while (Math.abs(x2 - x1) > 1e-4) {
x1 = x2;
x2 = x1 / 2.0 + a / (2 * x1);
}
return x2;
}
世界上所有的不公平都是由于当事人能力不足造成的.