Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Cube Root using Iteration

807603Feb 13 2008 — edited Feb 13 2008
Hi all, I have the following program that calculates a square root using the Babylonian algorithm. How can I tweak the code to now calculate the cube root using the same iteration method? Thanks in advance for any suggestions.
import java.util.Scanner;


public class CubeRoot {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		double n = 0;
		double guess = 0;
		double result = 0;
//		=============
		Scanner keyboard; 
        keyboard = new Scanner(System.in);
        System.out.println("This program demonstrates the cube root algorithm.");
        System.out.println("");
        
        System.out.println("Please enter a positive integer:");
        n = keyboard.nextInt();
        guess = n/2.0;
        System.out.println("You entered "+n);
        System.out.println("");
//		=======================
        for(int ii=0;ii<n;ii++)
        {
        	result = n / guess;
			guess = (guess + result) / 2.0;
        }
        System.out.println("The square root of "+n+" is:");
        System.out.printf("  [ %4.2f ]", result);
       



	}// main

}//class CubeRoot
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 12 2008
Added on Feb 13 2008
1 comment
200 views