wii
wii

Reputation: 13

I entered the correct value but the wrong value is printed

I entered the correct value but the wrong value is printed. (*Quotient is displayed up to the first decimal place.)

System.out.printf ("What is quotient of %d / %d ? ", n1, n2);
double answer1 = s.nextDouble();  //enter quotient

System.out.printf("What is remainder of %d / %d ? ", n1, n2);
double answer2 = s.nextDouble();  //enter remainder

if ((quotient == answer1) && (((n1-(quotient*n2)) == answer2)))
  System.out.print("Correct!");

else {  System.out.print("Incorrect: ");  //error point I think
System.out.printf("%d / %d = %f, Remainder: %f \n", n1, n2, quotient, (n1-(quotient*n2)));   }

When the problem is 6/7, if I enter the right answer 0.8 and the rest 0.4, "Incorrect: 6/7 = 0.800000, remainder: 0.400000" is displayed instead of "Correct!" What should I do?

Upvotes: 1

Views: 80

Answers (2)

SamratV
SamratV

Reputation: 226

Even though two floating point variables(say a & b) have the same value mathematically, their equality might not return true,i.e, a == b might not be true. Hence, we find the difference to see if the difference is negligible. So, try the following:

import java.util.*;

class Solution{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in);
        int n1 = 6, n2 = 7;

        System.out.printf ("What is quotient of %d / %d ? ", n1, n2);
        double answer1 = s.nextDouble();  //enter quotient

        System.out.printf("What is remainder of %d / %d ? ", n1, n2);
        double answer2 = s.nextDouble();  //enter remainder

        double num = answer1 * n2 + answer2; //calculate user's number
        if (Math.abs(new Double(n1) - num) <= 0.1f)
            System.out.print("Correct!");
        else{
            System.out.print("Incorrect: ");  //error point I think
            double quotient = new Double(n1) / new Double(n2);
            double remainder = new Double(n1) - quotient * new Double(n2);
            System.out.printf("%d / %d = %f, Remainder: %f \n", n1, n2, quotient, remainder);
        }
    }
}

Upvotes: 0

derpirscher
derpirscher

Reputation: 17400

This is due to floating point operations and precision. The difference may be in the 10th place after the comma. Therefore you should not compare floats with == but check if their difference is below a certain threshold.

double a = ...;
double b = ...;

if (Math.abs(a-b) < 0.0001) {
  //Consider as equal
} else { 
  //Consider as unequal
}

Upvotes: 4

Related Questions