(Java) Write a program that reads in two double numbers followed by an integer (
ID: 3679948 • Letter: #
Question
(Java) Write a program that reads in two double numbers followed by an integer (say n). The goal of the program is to check if the two numbers are equal to n significant digits.
Input
The input will be one or more lines of three numbers. The first two numbers are doubles and represent the two numbers that are to be compared. The third number is an integer and represents the number of significant digits to check (for equality of the two numbers).
Output
The output will show the difference up to 10 decimal places (as shown in sample output) and then whether the numbers are equal or not.
Sample Input
1.112 1.113 2
1.123 1.124 3
Sample Output
difference = 0.0010000000 , Numbers are equal to 2 decimal places
difference = 0.0010000000 , Numbers are not equal to 3 decimal places
HINTS
1. To print difference to 10 decimal places use System.out.printf("%.10f", diff);
2. Compare difference of numbers against 1.0 / Math.pow(10, n) where, n is the integer being read in by the program.
3. Make sure to take the absolute value of the difference when you compare. Use Math.abs method to get the absolute value.
Explanation / Answer
package com.he.capillary.chegg1;
import java.util.Scanner;
public class CompareNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter numbers : ");
String line = scanner.nextLine();
String str[] = line.split(" ");
double firstNum = Double.parseDouble(str[0]);
double secondNum = Double.parseDouble(str[1]);
int num = Integer.parseInt(str[2]);
long tempFirst = (long) (firstNum * Math.pow(10, num));
long tempSecond = (long) (secondNum * Math.pow(10, num));
if (tempFirst == tempSecond) {
System.out.printf("%.10f", Math.abs(firstNum - secondNum));
System.out.print(" , Numbers are equal to " + num + " decimal places ");
} else {
System.out.printf("%.10f", Math.abs(firstNum - secondNum));
System.out.print(" , Numbers are not equal to " + num + " decimal places ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.