首页 > 解决方案 > 找不到百分比 - 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;
        }
    }
}

标签: java

解决方案


countVotes是一个整数。当你这样做时(double)(countVotes/6)(countVotes/6)首先发生。这评估为 0,因为两者都是 int。要解决此问题,请将 6 更改为 6.0。

(double)(countVotes/6.0)*100

在这种情况下,不再需要演员加倍。

(countVotes/6.0)*100


推荐阅读