• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Simple Arithmetic Problem

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi there, wanna check if i am coding this wrongly:



Shouldn't the answer, SimPercent, be 24.4 How come I am getting 0.0

Tks!
 
Ranch Hand
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
integer division truncates everything after the decimal point, so if you had an expression that was supposed to result in 0.244 (i.e. 23/43) you would only get the 0.
You should make sumOfVotes and howLong ints, or cast the expression to an int.

Hunter
 
Jerri Loh
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks hunter,

but yr suggestion doesn't work out.

But i got it solved.
Kramed from Daniweb:

The problem is you are doing integer division, which will truncate rather than round as you expect. In Java, 5/2 = 2 and 2/5 = 0 . To fix this problem, you need to make one of the operands in the division a floating point type (either float or double). Again, in Java, (float)5/2 = 2.5 and 2/(double)5 = 0.5 .


 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
actually both of my suggestions work:





both print: 24.46808510638298

Hunter

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your suggestion would have worked if you hadn't accidentally written "int" instead of "double" .
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Haha, I read my own post 5 times and didn't notice that; thank you for pointing it out.


Hunter
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic