java - 找不到百分比 - JAVA
问题描述
所以我有这个问题,找到百分比不起作用,我真的不知道为什么,所以我的任务是找到选举候选人的数量和选民的数量,最后它应该显示百分比票数示例如果有 3 名候选人和 6 名选举人,第 1 名候选人获得 3 票,第 2 名获得 2 票,第 3 名获得 1 票,则应显示:50.00%、33.33%、16.67%。
下面是我的代码,它得到了正确的票数,但是当涉及到百分比时,它在所有情况下都只显示 0.0%。我希望你们能帮助我。
import java.util.Scanner;
public class ElectionPercentage {
public static void main(String[]args){
//https://acm.timus.ru/problem.aspx?space=1&num=1263
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many candidates are : ");
int candidates = sc.nextInt();
int [] allCandidates = new int[candidates];
int startingCandidate = 1;
for(int i = 0; i < candidates;i++){
allCandidates[i] = startingCandidate++; //now value of the first element will be 1 and so on.
}
//for testing System.out.println(Arrays.toString(allCandidates));
System.out.println("enter the number of electors : ");
int electors = sc.nextInt();
int [] allVotes = new int[electors];
for(int i =0;i < electors;i++){
System.out.println("for which candidate has the elector voted for :");
int vote = sc.nextInt();
allVotes[i] = vote; //storing all electors in array
}
System.out.println();
int countVotes = 0;
double percentage;
for(int i = 0;i<allCandidates.length;i++){
for(int k = 0; k < allVotes.length;k++){
if(allCandidates[i]==allVotes[k]){
countVotes++;
}
}
System.out.println("Candidate "+allCandidates[i]+" has : "+countVotes+" votes.");
percentage = ((double)(countVotes/6)*100);
System.out.println(percentage+"%");
countVotes = 0;
}
}
}
解决方案
countVotes
是一个整数。当你这样做时(double)(countVotes/6)
,(countVotes/6)
首先发生。这评估为 0,因为两者都是 int。要解决此问题,请将 6 更改为 6.0。
(double)(countVotes/6.0)*100
在这种情况下,不再需要演员加倍。
(countVotes/6.0)*100
推荐阅读
- vue.js - vue2-editor 不适用于 nuxt js。参考错误:文档未定义
- python-3.x - Python:基于类属性排序
- javascript - 计算给定布尔值(JavaScript,NodeRed)的 ON 和 OFF 之间的操作时间
- typescript - 推断链式函数的 ReturnType<>
- java - 如何使用 android studio 中的两个活动在 sqlite 数据库中创建两个表
- android - 如何在 Yandex mapkit 中为折线设置动画
- javascript - 我想要在我的 discord.js 机器人中使用的特定命令
- visual-studio-code - 设置 Vscode 用于调试 Eigen
- python - NameError:未定义名称“日志记录”
- flutter - 在 null 安全之后,PreferredSize 小部件有什么用?