Questtion3: Modify Sqrt.java so that it reports an error if the user enters a ne
ID: 3638033 • Letter: Q
Question
Questtion3: Modify Sqrt.java so that it reports an error if the user enters a negative numberand works properly if the user enters zero.
public class Sqrt {
public static void main(String[] args) {
// read in the command-line argument
double c = Double.parseDouble(args[0]);
double epsilon = 1e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision
is achieved
while (Math.abs(t - c/t) > epsilon*t) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
}
Explanation / Answer
public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]); if (c < 0) { System.out.println("Error: number cannot be negative"); } else if (c == 0) { System.out.println(0); } else { double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.