0

I'm having some problem with my code. It works fine when I compile it until I get to the point when the numbers divide. I'm not getting numbers with decimal, only zero. As you can see, I already changed the last variables to double but it didn't have any meaningful result.

What must I do to change this?

        int[] arr = new int[2];
        System.out.println("enter two numbers: ");
        arr[0] = sc.nextInt();
        arr[1] = sc.nextInt();

        int summa = arr[0]+arr[1];

        System.out.println("What's "+arr[0]+" + "+arr[1]+" ?");
        int vad = sc.nextInt();

        if (summa == vad)
            System.out.println("Correct!");
        else
            System.out.println("Wrong - The right answer is "+summa);


        int summa2 = arr[0]-arr[1];
        System.out.println("What's "+arr[0]+" - "+arr[1]+" ?");
        int vad2 = sc.nextInt();

        if (summa2 == vad2)
            System.out.println("Correct!");
        else
            System.out.println("Wrong - The right answer is: "+summa2);


        int summa3 = arr[0]*arr[1];
        System.out.println("What's "+arr[0]+" * "+arr[1]+" ?");
        int vad3 = sc.nextInt();

        if (summa3 == vad3)
            System.out.println("Correct!");
        else
            System.out.println("Wrong - The right answer is "+summa3);


        double summa4 = arr[0]/arr[1];
        System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
        double vad4 = sc.nextInt();

        if (summa4 == vad4)
            System.out.println("Correct!");
        else
            System.out.println("Wrong - The right answer is "+summa4);



}

}

2 Answers 2

4

1 you are reading int it should be double .
2 You need to cast to double check code below

    double summa4 = ((double)arr[0])/arr[1];
    System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
    double vad4 = sc.nextDouble();

    if (summa4 == vad4)
        System.out.println("Correct!");
    else
        System.out.println("Wrong - The right answer is "+summa4);
Sign up to request clarification or add additional context in comments.

1 Comment

and 3) compare doubles using a range like (summa4 <= vad4 + 0.01 && summa4 >= vad4 - 0.01) testing doubles for equality is a problem because of floating point artifacts.
2

Although summa4 variable is of type double, but it's calculation is done in integer division. Therefore, the result would not have any decimal place.

For example, 5/2 = 2 and not 2.5 if both 5 and 2 are integers or values stored in int type variable.

change:

double summa4 = arr[0]/arr[1]; 

to

double summa4 = 1.0*arr[0]/arr[1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.