Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : D words : division.
// sample divisions int i = 7; int j = 2; int k = i / j; // gives 3 double d = (double) i / ( double) j; // gives 3.5 double oops = (double) ( i / j ); // gives 3.0 double shortcut = ((double) i ) / j; // gives 3.5, j is promoted to double automatically. double surprise = 1.0d / 10.0d; // gives approximately 0.1. // 0.1 is a binary repeater fraction.
Floating point division always seems to be a wee bit off from what you would expect. That is because many common decimal fractions are repeaters when expressed in binary that Java uses internally.
In Java you take the remainder with the % operator. In Java, the sign of the remainder follows the dividend, not the divisor.
Be especially careful when corralling random numbers into a smaller range with the modulus operator. Java division does have the Euclidean property. When you multiply the quotient by the divisor and add the remainder you get back to the dividend. Java division is truncated division.
(dividend >= 0) ? (dividend / divisor) : ( (dividend - divisor + 1 ) / divisor );
(dividend >= 0) ? ( (dividend + divisor - 1 ) / divisor) : (dividend / divisor );
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 5436. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/division.html | J:\mindprod\jgloss\division.html | |||