David
David

Reputation: 7

3 / 2: Division paradox (Java)

I just wrote this and I can't find the reason it won't solve the division as expected. Can someone please explain what's going on in here?

Here's the code:

/*
3/2
 */
package paradoja;

public class Paradoja {

    public static void main(String[] args) {
        float dividendo, divisor, resto, cociente;

        dividendo = 3;
        divisor = 2;
        resto = dividendo % divisor;
        cociente = dividendo / divisor;

        System.out.printf("--------DIVISION--------\n");
        System.out.printf("El propósito es dividir 3 entre 2 y, a continuación, hacer la prueba.\n------------------------\n");
        System.out.printf("Dividendo = %.2f\nDivisor = %.2f\nCociente = %.2f\nResto = %.2f\n", dividendo, divisor, cociente, resto);
        System.out.printf("--------PRUEBA--------\n");
        System.out.printf("%.2f * %.2f + %.2f = %.2f (¿?)\n----------------------\n", cociente, divisor, resto, cociente * divisor + resto);
    }

}

It's just a 3/2 division and further test. It returns 4 instead of 3. Thank you for your time!

Upvotes: -1

Views: 164

Answers (2)

Joseph Larson
Joseph Larson

Reputation: 9058

Okay. resto = the remainder of an integer division - 3 % 2 = 1.

But you're not doing integer division. You're doing floating point division. So your last calculation is:

cociente * divisor + resto
1.5 * 2 + 1 = 4

If you stored all this in ints instead of floats, it would be doing what you expect. Or if you converted to ints in your final calculation, it would work the way you expect.

Upvotes: 0

Josh Evans
Josh Evans

Reputation: 655

I have commented the values of your variables at each point in the program.

package paradoja;

public class Paradoja {

    public static void main(String[] args) {
        float dividendo, divisor, resto, cociente;

        dividendo = 3;
        divisor = 2;
        resto = dividendo % divisor;     // resto = 3.0 % 2.0 = 1.0
        cociente = dividendo / divisor;  // cociente = 3.0 / 2.0 = 1.5

        System.out.printf("--------DIVISION--------\n");
        System.out.printf("El propósito es dividir 3 entre 2 y, a continuación, hacer la prueba.\n------------------------\n");
        System.out.printf("Dividendo = %.2f\nDivisor = %.2f\nCociente = %.2f\nResto = %.2f\n", dividendo, divisor, cociente, resto);
        System.out.printf("--------PRUEBA--------\n");
        // The last parameter passed to the System.out.printf() statement is cociente * divisor + resto = 1.5 * 2.0 + 1.0 = 4.0
        System.out.printf("%.2f * %.2f + %.2f = %.2f (¿?)\n----------------------\n", cociente, divisor, resto, cociente * divisor + resto);
    }

}

Upvotes: 1

Related Questions