Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Algorithm not working?  RSS feed

 
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!

 
Ranch Hand
Posts: 754
Eclipse IDE Java
 
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...

 
Marshal
Posts: 58336
178
  • 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
Boost this thread!