java - Doing one more iteration after DO-While loops stops? -
i writing babylonian algorithm computing square root of positive number, , iteration should keep going until guess within 1% of previous guess. code have written gets iteration going 1 before error 1%. how can make 1 more iteration ? question straight, there way tell iterate untill error <1% ?
import java.util.scanner; public class sqrt { public static void main(string[] args){ scanner kb = new scanner(system.in); system.out.print("\nplease enter desired positive number in order find root of two: "); double num = kb.nextdouble(); double guess=0; double r, g1, error; if (num>=0){ guess = num/2; do{ r = num/guess; g1 = guess; guess = (guess+r)/2; error = (guess-g1)/guess; if (error<0){ error = -error; } } while(error>0.01); system.out.println("the square root of number " + num +" equal " +guess); } else { system.out.println("sorry number entered not positive number, , not have root of two"); } } }
add new counter gets increased in (former) exit loop condition.
int exit = 0; { ... if (error <= 0.01) { exit++; } } while (exit < 2);
Comments
Post a Comment