Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange results using % on doubles?

Status
Not open for further replies.

tonedef

Programmer
May 24, 1999
64
US
Does anyone know why I am getting strange results when using the % operator. (It could be on other things as well, but this is when I noticed it.)

I'm running Win 98, Sun JDK1.3, compiled at dos prompt using javac and ran at dos prompt using java. Following is the simple program I used to pinpoint the error and the output.

[tt]
class Modulus
{
public static void main (String args[])
{
int x = 42;
double y = 42.3;

System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
[/tt]

OUTPUT

x mod 10 = 2
y mod 10 = 2.99999999999997

Thanks,

tone
 
There probably is no error.
I'll take a guess that it's simply because the maths done on your double is done as double and hence produces all the normal rounding errors. I get the identical result if I type the calculation into my browser.

If the result looks ugly, then the solution is to use number formats to make it look neater. Look at:


and page back & forward through the tutorial
 
Isn't mod's definition really that it takes 2 int arguments? Jim

oracle, vb
 
The % operator doesn't have to take integers but for logical reasons I don't see any reason to use anything other than integers.
Wushutwist
 
hello !

the % modulus for you it seems jsut taking 42.3 divided by 10 ie 2.3 which is actuall the result.but the system is actually and blindly divivding the number as

10)42.3(4.
40
-------
2.3............

and so on so forth so there is actually division logic called in the compilers and not jsut giving of the reminder.


so there are the strange results.


if you are satisfied with this result do reply
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top