Question

Hello can't figure out why I can't get right result for startE

just a simple program, to illustrate the problem.

"NUMBER CLASS"

public class Number {

    public static void main(String[] args) {
        Grow big = new Grow();
        big.growing();
    }}

"GROW CLASS"

public class Grow {
    private int startE = 50000 / 1 / 2;
    private int startC = 50000 / 1 / 3;

    public void growing() {

        for (int i = 0; i < 10; i++) {

            startE = startE + (((50000 * (13 / 20)) - (50000 * (1 / 2))) / 200);
            startC = startC + ((50000 / 1 / 2 - 50000 / 1 / 3) / 75);

            System.out.println(startE);
            System.out.println(startC);

        }
    }}

You will see that 'startC' does as expected, however I am getting no joy with 'startE' If you can help that would be great

What it prints out on console.

25000
25000
25000
25000
25000 etc
Was it helpful?

Solution

You have this problem because of how integer division works in Java:

startE = startE + (((50000 * (13 / 20)) - (50000 * (1 / 2))) / 200);

When you do 13/20 above, it returns 0 because all the values following the decimal point are discarded in ints. This is equivalent of the floor in math. When you multiply 50000 with 0, you get a 0. Same thing with 1/2. It becomes 0 and 0 multiplied by anything is 0.

Your startE value starts at 25000. When you add 0 to 25000 you get 25000. That is the reason you keep seeing 25000 in the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top