This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# A variable is 0

Alex MG
Greenhorn
Posts: 1
Hi,

I'm new in Java and to learn I'm typing and testing code. I have the following code:

What I want to do is to display the sum of the numbers after dividing them. The problem is the result of r and res variables that always is 0 and I don't know why.

What's wrong?

Thanks.
[ January 23, 2005: Message edited by: Ilja Preuss ]

Ilja Preuss
author
Sheriff
Posts: 14112
Please use code tags in the future - I will add them for you in this case...

Mark Vedder
Ranch Hand
Posts: 624
The problem is that you have declared your variables as type int. Therefore when doing the division (this.n/this.d and this.nm/this.nd) the results (0.5 and 0.66666666667) are being cast to type int and being set to of 0 and 0 (since the fraction is truncated off).

Change your variables and parameters n, d, nm, and nd to be of type float and you will get the result of 1.1666667.

Layne Lund
Ranch Hand
Posts: 3061
Better yet, don't do the division. I would guess that "fraccion" is your language's equivalent to the English "fraction". A very OO approach to this code, would be to have summ() return a fraccion, rather than a float. You can do this with a single line of code, if you understand the algebra for adding fractions together.

With that said, you should also look into "integer division" as it is called. You should be able to google for this topic to find out why you are getting a 0 as the answer.

HTH

Layne

[ January 23, 2005: Message edited by: Layne Lund ]
[ January 23, 2005: Message edited by: Layne Lund ]

Mark Vedder
Ranch Hand
Posts: 624
As another alternative, if you wanted to ensure that your method only took 4 int's as parameters (since it appears you are trying to mimic a pair of fractions), you could cast them to float's as you do the calculation:

This would "prevent" two products of the division from being cast to int's.

Layne made his post while I was typing this second post. I agree that a true object oriented way of doing it would be to have your method return a "fraction" (or faccion) object. If you are not quite ready for that yet in your Java knowledge, give the casting to a float as I suggest here a try.
[ January 23, 2005: Message edited by: Mark Vedder ]

Marilyn de Queiroz
Sheriff
Posts: 9059
12
Hi, Alex MG

Welcome to JavaRanch! Please adjust your display name to meet the JavaRanch Naming Policy. Unfortunately your last name does not comply. You can change it here.

Thanks!