private static int votePercentage() {
int players = 0;
for (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, that the returning nubmer is not an int, and is a double because 1/2 = 0.5. Therefore it will always return 0, unless the votes division by players is not a double and is a int.
Basically I want to return the percent of the voted users, out of all online players.
Is there a solution for this? maybe a java class or built-in function?
You need to use float
(remember to change the function's return type!):
float avg = ((float)votes / players);
int
can only store integers; it cannot store decimals. Only float
and double
(for double precision) can store decimal numbers.
You could also switch around your formula:
return ((votes * 100) / players);
Note that this will round down to the next integer.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments