Java math problems - Vote count to percentage

Jony Kale
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?

tckmn

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Replace Vote Count with a Percentage System for Jquery upVote

From Dev

Problems With Percentage

From Dev

Java Vote Program Error

From Dev

Javascript Difference Percentage Math

From Dev

how to create a java function that makes random math problems.

From Dev

MySQL vote count for each row each column

From Dev

Math.Round problems

From Dev

Count records where their vote count in another table meets a criterion

From Dev

Count records where their vote count in another table meets a criterion

From Dev

Calculate Count as Percentage

From Dev

Count and percentage ranges

From Dev

Count and Percentage of skill ratings

From Dev

groupby count and percentage

From Dev

Calculating Percentage of COUNT with GROUP BY

From Dev

PostgreSQL - Percentage Count

From Dev

SQL Percentage Complete with COUNT and Remaining Percentage

From Dev

Order results by time added, but rank them by vote count

From Dev

How to get the count of voters who don't vote on a specific poll

From Dev

Rails poll app check if vote count for option has reached a value

From Dev

math - add percentage at value, but limit to a max?

From Dev

Async Await Loop/Math problems

From Dev

Math.random() problems in method

From Dev

Math application to calculate advance problems

From Dev

problems with compiling openMP and math library

From Dev

list/math problems returns zero

From Dev

Bash: Date/Time math problems

From Dev

MYSQL / SQL Count Percentage Query

From Dev

Pandas Percentage count on a DataFrame groupby

From Dev

Getting percentage from count in Hive