• Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple Arithmetic Problem  RSS feed

 
Jerri Loh
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • 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!
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • 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
  • 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 Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
actually both of my suggestions work:





both print: 24.46808510638298

Hunter

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • 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 Linux VI Editor
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!