Reputation: 1217
I'm trying to divide two numbers to get a percentage, then print it. Here's the relevant method:
public void process_winner(String candidates[], int votes[])
{
double percent = (mostVotes / votes.length) * 100;
if (mostVotes > votes.length / 2)
System.out.println("Winner: " + candidates[mostVotesIndex] + "(" + percent + "%)");
else
System.out.println("None (no majority)");
System.out.println("");
}
the problem line is:
double percent = mostVotes / votes.length;
mostVotes
is an int
, with a value of 6, and votes.length
is 10. I verified this using the debugger.
It's showing a value of 0.0 for my percent variable, when it should show 60.0
Upvotes: 1
Views: 2198
Reputation: 1
You need to change this or "cast" it to a double. what you have done is this
double percent = (mostVotes / votes.length) * 100;
what you think you are doing is this:
now what is actually happening is this:
Know after explaining what you have done wrong i will explain what is right, and explain it to you.
we then recieve 60. <--- which is your answer.
(mostVotes*100) / votes.length
The reason behind this is because you never really meet a decimal number in this way of calculation.
You of course can just change mostVotes into a double. But doing this is just a more convienent way.
This is more of a "algorithmic problem" and not a progrtamming problem.
Upvotes: 0
Reputation: 45070
You need to cast it to double
, because otherwise it will be an integer division, and thus, the precision will be lost.
double percent = ((double) mostVotes / votes.length) * 100;
Upvotes: 3
Reputation: 13566
make your formule as (mostvotes * 100)/votes.length
In your case, the execution is:
mostVotes/votes.length
causes 6/10 which is integer divisionWhen you change it to double percent = (mostVotes * 100 ) / votes.length;
The order of execution becomes
mostVotes * 100
i.e. 6 * 100600/votes.length
i.e. 600/10 = 60This should give you correct output
Upvotes: 1
Reputation: 19294
This is Integer division, and works as expected.
If you want to get double
value when dividing integers, use:
double percent = mostVotes * 1.0 / votes.length;
BTW, in order to get percentage, you need to multiple it by 100:
double percent = mostVotes * 100.0 / votes.length;
Upvotes: 1
Reputation: 9038
You need to cast to double
, or change the operation order.
Do this:
double percent = (mostVotes * 100 ) / votes.length;
Upvotes: 5