This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes strange result of Modulo Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "strange result of Modulo " Watch "strange result of Modulo " New topic

strange result of Modulo

Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

System.out.println(-9+"%"+-7+"="+-9%-7); // result -2

System.out.println(-7.6+"%"+-2.9+"="+7.6%2.9);// 1.7999999999999998

double d=-7.6;
double e=-2.9;
double f=d%e;

I understand that sign of result is of left operand, but when both operands are negative real numbers, result is +ve. Why?
Jhakda Velu
Ranch Hand

Joined: Feb 26, 2008
Posts: 167
well, the code snippet you posted gives a negative result when both operands are negative.
In the second sysout, though you have given a negative sign to print to console, while doing th actual calculation, you missed it, thats why the confusion i think.
Let me know if i understand it properly(or if you ment something else in your problem statement)

[ April 09, 2008: Message edited by: Jhakda Velu ]
[ April 09, 2008: Message edited by: Jhakda Velu ]

If I become filthy rich, I'll sponsor research for painless dental treatment at Harvard Medical School. Thats why,I'm learning Java.I have 32 teeth, 22 are man made.
Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

You are right, I missed it
shankar reddy
Ranch Hand

Joined: Jun 04, 2007
Posts: 71
For Example.....
9(Lopenrand) %(Operator) 8(Roperand)

Here what ever the sign of left operand, will added to the result, which is not depend on the right operend. I hope you understand. Reply if you got the point.

Java Lover<br /> <br />Shankar Reddy <br />SCJP1.4 (88%)
Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

I understood where I made a mistake.
Have you checked out Aspose?
subject: strange result of Modulo
It's not a secret anymore!