This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Algorithm not working?

 
Ashley Kin
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, my algorithm (wins/numberOfGames)*100 is not working; it's printing out 0 every time, even though all four other variables are working fine.
Is my algorithm itself not correct?
I just assumed win% means the percentage of games won.
Thanks as always!

 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
 
Bob Bilfred
Greenhorn
Posts: 7
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There isn't really a problem with the code since it does what was typed. Since both "wins" and "numberOfGames" are integers, when you divide them, you also get an integer. This calculation will also result in a decimal number, not an integer. Therefore, dividing two integers, say 6 and 10, will not be 0.60, it will be 0 since integers remove the numbers after the decimal point. Therefore, we need to cast "wins/numberOfGames" to a double. In order to do this, write the following instead...

 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Bob Bilfred

Another way to do it is to move the 100 * to the beginning of the formula. () unnecessary, and can actually cause errors, so no (). Beware: you can get overflow problems with large numbers, and 100 * 999 / 1000 will come out as 99%, not 99.9%.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic