在特定数量的小数位后停止循环

时间:2018-04-22 21:43:57

标签: loops numbers double square-root

我有一个程序可以在没有Math.sqrt方法的情况下计算数字的平方根。我做了这个但是.....如果数字不是一个完美的正方形,循环继续(正确),如何在基本java中的一些小数位后停止循环:) 谢谢!

import java.util.Scanner;

public class SquareRootMethod {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);

    System.out.println("Please enter a number to square root: ");
    double Number = sc.nextInt();
    double Answer = FindSquareRoot(Number);
    System.out.println(Answer);



}



public static double FindSquareRoot(double NumberToRoot) 
{

    double Guess = NumberToRoot;
    double GuessAmmount = NumberToRoot;

    do
    { GuessAmmount = GuessAmmount/2;
    if (Guess*Guess >NumberToRoot);
    { Guess = Guess - GuessAmmount; }
    if (Guess*Guess <NumberToRoot)
    {Guess = Guess + GuessAmmount; }
    }
    while (Guess*Guess != NumberToRoot);
    return Guess;

}

}

1 个答案:

答案 0 :(得分:1)

如何在数字上设置某种精度?

public static double findSquareRoot(double numberToRoot) {
    double guess = numberToRoot;
    double guessAmount = numberToRoot;

    do {
        guessAmount = guessAmount / 2;
        if (guess * guess > numberToRoot) {
            guess = guess - guessAmount;
        }
        if (guess * guess < numberToRoot) {
            guess = guess + guessAmount;
        }
    } while (Math.abs((guess * guess) - numberToRoot) > 0.001);

    return guess;
}

诀窍在while行。