• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

please help. division on for loop and array.

 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In addition, if you want to get more precise values you should declare the numbers as doubles eg:

 
Danger, 10,000 volts, very electic .... tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic