Write a program that reads in two floating-point numbers and tests whether they
ID: 3527108 • Letter: W
Question
Write a program that reads in two floating-point numbers and tests whether they are the same up to two decimal places. here are two sample runs. Enter two floating-point numbers: 2.0 1.99998 They are the same up to two decimal palces. Enter two floating-point numbers: 2.0 1.98999 They are different. import java.util.Scanner; class FloatingPoint { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter two floating-point numbers: "); double x = sc.nextDouble(); double y = sc.nextDouble(); if (x== y) System.out.println("They are the same up to two decimal places."); else System.out.println("They are different"); } } This is the code I have come up with so far which i know is incorrect. I need help writing the code that checks these numbers up to two decimal places to see if they are the same or different.Explanation / Answer
First, you want to use a scanner to read input values: Scanner s = new Scanner(System.in); System.out.print("Enter first number: "); double d1 = s.nextDouble(); System.out.print("Enter second number: "); double d2 = s.nextDouble(); Second, you can compare rounded to two decimal places by simply multiplying by 100, adding 0.5, and converting to int (assuming nobody is going to enter a 20-digit number that would overflow an int). Converting to int will truncate, so you have to add 0.5 so that you get the effect of rounding: int d1rounded = (int) (100.0 * d1 + 0.5); int d2rounded = (int) (100.0 * d2 + 0.5); if (d1rounded == d2rounded) { // Same when rounded to 2 decimal places } else { // Not the same } And you can use Math.abs to determine a difference between two numbers as it returns the absolute value: double diff = Math.abs( d1 - d2 ); if (diff < 0.01) { // Differ by less than 0.01 } else { // Differ by 0.01 or more } If I had to do the assignment as stated, I would do it numerically as above. You can also use DecimalFormat to print numbers in a certain fashion: DecmalFormat twoDecimalDigits = new DecimalFormat("#.00"); String d1Formatted = twoDecimalDigits.format( d1 ); String d2Formatted = twoDecimalDigits.format( d2 ) ; if ( d1Formatted.equals( d2Formatted ) ) { // same when rounded to two digits } else { // not the same } ... but that is really kind of hokey.Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.