Java math problems - Vote count to percentage -


private static int votepercentage() {     int players = 0;     (int p = 0; h < players; p++) {         if (playersonline[p] != null) {             players++;         }     }     int votes = voters.size();     int avg = (votes / players);     return (avg * 100); } 

votes: 1 players: 2 return: 0

votes: 2 players: 2 return: 100

problem

the problem is, returning nubmer not int, , double because 1/2 = 0.5. therefore return 0, unless votes division players not double , int.

basically want return percent of voted users, out of online players.

is there solution this? maybe java class or built-in function?

you need use float (remember change function's return type!):

float avg = ((float)votes / players); 

int can store integers; cannot store decimals. float , double (for double precision) can store decimal numbers.

you switch around formula:

return ((votes * 100) / players); 

note round down next integer.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -