Skip to content

Latest commit

 

History

History
50 lines (35 loc) · 2 KB

File metadata and controls

50 lines (35 loc) · 2 KB

Java 程序:不使用sqrt查找数字的平方根

原文: https://beginnersbook.com/2019/02/java-program-to-find-square-root-of-a-number-without-sqrt/

找到数字的平方根非常容易,我们可以使用Math.sqrt()方法找出任​​意数字的平方根。但是在本教程中我们将做一些不同的事情,我们将编写一个 java 程序来找到没有sqrt()方法的数字的平方根

Java 示例:不使用sqrt()方法查找平方根

在下面的程序中,我们创建了一个方法squareRoot(),在方法中我们编写了一个方程式,用于查找数字的平方根。对于方程式,我们使用while循环

package com.beginnersbook;
import java.util.Scanner;
class JavaExample { 

    public static double squareRoot(int number) {
	double temp;

	double sr = number / 2;

	do {
		temp = sr;
		sr = (temp + (number / temp)) / 2;
	} while ((temp - sr) != 0);

	return sr;
    }

    public static void main(String[] args)  
    { 
	System.out.print("Enter any number:");
	Scanner scanner = new Scanner(System.in);
	int num = scanner.nextInt(); 
	scanner.close();

	System.out.println("Square root of "+ num+ " is: "+squareRoot(num));
    } 
}

输出:

Java Program to find out the square root of a given number

相关的 Java 示例

  1. Java 程序:检查完美平方数
  2. Java 程序:打破数字
  3. Java 程序:查找两个数字的 GCD
  4. Java 程序:显示斐波那契序列