비율을 찾을 수 없습니다 - 자바를

해피 Gashi :

그래서 난 내 임무는 선거 후보자의 수와 선거인과 끝 번호를 찾을 수 있습니다, 그래서 이유는 투표 예제의 비율을 보여 주어야 비율 나던 작업과 정말 해달라고 노하우를 찾는이 문제가되는 경우가 3 개 후보 6 선거인하고 1 차 후보 2 2 표를 얻을, 3 표를 가져오고 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;
        }

    }

}




rzwitserloot :

countVotesint로 6도 INT이다. 따라서, (countVotes/6)끝 부분에서, 정수 나누기입니다, 당신의 코드이다. 정수 부문의 11/6은 1 5/6 그것은 모든 소수를 전지로 반올림 0입니다. 당신이 나중에 두 배를 캐스팅해야 할 특히 때문에 즉, 당신이 원하는 아마 아니다.

당신은 잘못된 일을 캐스팅하고 있습니다. 그러나 당신도 전혀 캐스트가 필요하지 않습니다; 양쪽 더블 경우, 모든 것은 이중 분할된다. 그래서, 대신 : percentage = ((double)(countVotes/6)*100);시도percentage = 100.0 * countVotes / 6.0;

또한, 아마도, 그 6은 정말 변수가 될 것이 투표 수가 총 #, 아니? electors, 이렇게 :percentage = 100.0 * countVotes / electors;

우리가 100.0 수단 수학 킥오프 사실은 두 번 모두 수학 길 아래로 수 있습니다.

추천

출처http://43.154.161.224:23101/article/api/json?id=27972&siteId=1