0

My apologies if the title is a bit confusing I had some trouble trying to word what I was trying to say.

Here is my code:

public class Assignment3 {

    public static void main(String[] args) {
        int A = 100;
        int B = 20;
        int C = 30;
        int X = 4 * A;
        int Y = 3 * (B + C);
        int Z = X / Y;

        System.out.println("The value of A is " + A + ".");
        System.out.println("The value of B is " + B + ".");
        System.out.println("The value of C is " + C + ".");
        System.out.println("The answer is " + Z + ".");

    }

}

It keeps giving me 2 as the answer when I know the answer is 2.6 repeating. Any ideas why and how I can fix it? Thanks in advance.

cpitt6477
  • 51
  • 4

2 Answers2

3

Both X and Y are integers (non decimal values). If you perform integer division, the decimal is truncated, leading to an unexpected answer.

Aditya R
  • 417
  • 4
  • 13
1

Two things you have to do. - Change the type of Z to float. - Cast either A or B to float in the division, as both of them are integers.

Try this and you will get the correct result:

float Z = (float) X / Y;
Nguyen Tuan Anh
  • 1,016
  • 7
  • 14