Tuesday, July 28, 2009

How do you get the remainder in division for Java? In other words how would you write that down in code?

Yea i just want the remainder. The division is going to be something like y/19. The variable y is actually going to be whatever the user inputs when constructing the object year. But again all I'm looking for is how to write in code to get only the remainder. Also how can i just get the quotient and not the remainder? It's not really a math question, just a question on how to write it in Java.

How do you get the remainder in division for Java? In other words how would you write that down in code?
For the remainder, use y%19. % is the modulus operator and will divide y by 19, then return the remainder.





int x = y % 19;





To get the full value, you could use the round function:





int x = Math.round((y/19));





but that will round the number which could make it larger and that might not be what you.





Another option would be





int x = (y/19)-((y%19)/19);





This would find the actual value of the division, then subtract the remainder from that value to give you the whole number
Reply:The remainder of division is provided by the Modulus operator. It is usually the % sign.





5 / 2 = 2.5





5 % 2 = 1





To get just the quotient, just shove the answer into an integer variable rather than a double to chop off the decimal remainder.
Reply:There is an operator called the modulus operator (the '%' character), which returns the remainder of dividing one number into another. IE,





int a = 20;


int b = 15;


int r = a % b; // r gets 5.


No comments:

Post a Comment