| Author |
please help. division on for loop and array.
|
Jhedzkie Skies
Ranch Hand
Joined: Oct 28, 2009
Posts: 118
|
|
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
Joined: Oct 24, 2008
Posts: 171
|
|
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
|
OCPJP 85%
|
 |
Joe Lemmer
Ranch Hand
Joined: Oct 24, 2008
Posts: 171
|
|
In addition, if you want to get more precise values you should declare the numbers as doubles eg:
|
 |
 |
|
|
subject: please help. division on for loop and array.
|
|
|