• Post Reply Bookmark Topic Watch Topic
  • New Topic

please help. division on for loop and array.  RSS feed

 
Aron Jhed Amiscosa
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a problem here with division in array...

it looks like this...



but it always produce 0 as result...

first on the p1, logically it looks like, 3/total.., and the result type i have is on double. i am just wondering what im doing wrong...
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jhedzkie,

The int named total has a value of 41.

When you get down to the for loop the following happens.

First each int in the p array will be divided by 41 (total).

This gives you an int result of less than 1. Note that the value here is still an int value, so precision will be lost. Therefore because the results in this case are all less than 1, the int value stores only the value 0 and not any of the stuff that would have been after the decimal point if you had divided two floating point values (eg double or float).

It is only after you have an int value of 0, that you assign this value to a double. A double is not an int, so this value must be cast as in:



but because int values will always fit into a double, the cast is implicit (ie Java takes care of it automatically), which is why it still works.

So process is:



results in an int value.



assign the result (an int value) and cast it to a double value (implicit cast).

Try swopping the above code for:



and you will see that you get non-zero values. But also notice that they are still rounded to zero because, as you used ints to do the calculation, you lost some precision.

Hope that helps

Joe
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In addition, if you want to get more precise values you should declare the numbers as doubles eg:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!