-1

Arithmetic Divide operator / returns the Quotient while Arithmetic modulus operator % returns the Remainder. What can be the reason when divide operator is used, it returns 0 value and modulus operator % returns 1. The expression is 1/10 and 1%10.

  • Note: I am using data type Integer: "int"
Omar S
  • 21
  • 3

2 Answers2

1

Like you said modulus is returning the remaining of a division.

As example:

1 % 10 = 0 R 1 <- This is the value Java returns

15 % 10 = 1 R 5 <- Here it returns 5 because it couldn't divide anymore

And 1 / 10 returns 0 because you are only using Integers. If you doesn't use a floating point number it doesn't return one and rounds down the result.

So if you want a floating point number you will need something like that:

    System.out.println(1 / 10); // -> 0
    
    System.out.println((float) 1 / 10);   // -> 0.1 //You can also use double for casting
    System.out.println(1.0 / 10);         // -> 0.1
    System.out.println(1 / 10.0);         // -> 0.1
    System.out.println(1.0 / 10.0);       // -> 0.1
Timeplex
  • 19
  • 3
0

Well, It has nothing to do with coding. We can simply understand it by solving basic maths. As we know:

Dividend / Divisor == > we get 2 Answers 
          Quotient and Remainder

If the Remainder is 0, the Dividend is completely divided by Divisor with parts of Quotient.

As in your suggested example, 1/10 actual Answer is 0.1 which is a float,

In your Java code, you must be looking for the integer value, which practically is not possible.

And obviously, 1%10 will give you 1, as 10 as divisor can not divide 1 as a dividend.

You can try it with a float variable. I hope you will get your expected results.

ZygD
  • 22,092
  • 39
  • 79
  • 102