I coded this short program to compute the square root of an input number using iteration (Babylonian Algorithm). However, my goal now is to execute as follows:
1)make a guess at the answer
2)compute root = n/guess << n is the input number
3) set guess = (guess +r) / 2
4) Go back to step 2 until the last two guess values are the same. I need to iterate until the guess is within 1% of the previous guess, and output the answer as a double to two decimal places. How can I cause the iteration to stop once I have two guess values that are the same? And also, how can I output the guess iterations as double to two decimal places using printf
andhave them print on separate lines?
CODE
import java.util.Scanner;
public class Babylonian {
/**
* @param args
*/
public static void main(String[] args) {
int n;
// =============
Scanner keyboard;
keyboard = new Scanner(System.in);
System.out.println("This program demonstrates the Babylonian algorithm.");
System.out.println("");
// =======================
System.out.println("Please enter a positive integer:");
n = keyboard.nextInt();
System.out.println("You entered "+n);
System.out.println("");
// =======================
double guess = n/2;
double r = 0.00;
for(int ii = 0; ii < 10; ii++)
{
r = n / guess;
guess = (guess + r) / 2;
System.out.println(guess);
}
// ===================================================
System.out.println("The square root of "+n+" is:");
System.out.printf(" [ %4.2f ]", r);
// =========================================
}// main
}// class Babylonian
This post has been edited by CrazyJ: 18 Feb, 2008 - 02:07 AM