我对Java有些新意,我正在进行一项任务,其中用户在选举中插入2名候选人的投票数,我需要计算每位候选人的总投票数的总百分比。我也不擅长数学,而且我被告知要声明一个“双”变量而不是施放它。我的输出打印百分比为0.0%,我认为我找到百分比的公式是错误的。无论如何,这是我的代码:
import java.util.Scanner;
public class Election {
public static void main (String []args) {
int y;
int n;
int c=0;
int t=0;
int csum=0;
int tsum=0;
int c2=0;
int t2=0;
int tie=0;
double cpercent;
double tpercent;
String i;
Scanner scan = new Scanner (System.in);
System.out.println ("Are there any more precincts to report?");
i = scan.next();
while (i.equalsIgnoreCase("y")) {
System.out.println ("Insert the number of votes for Polly Clitch");
c = scan.nextInt();
System.out.println ("Insert the number of votes for Ernest Truble");
t = scan.nextInt();
System.out.println ("Are there any more precincts to report?");
i = scan.next();
csum+=c;
tsum+=t;
if (c > t)
c2++;
if (c < t)
t2++;
if (c == t)
tie++;
}
System.out.println ("Polly Clitch's total amount of votes is " + csum);
System.out.println ("Ernest Truble's total amount of votes is " + tsum);
cpercent = (double) (csum/100);
tpercent = (double) (tsum/100);
System.out.println ("Polly Clitch's total amount of votes percentage is " + cpercent + "%");
System.out.println ("Ernest Truble;s total amount of votes percentage is " + tpercent + "%");
}
}
输出:
还有更多的区域要报告吗?
ý
插入Polly Clitch的投票数
48
插入欧内斯特·特鲁布的票数
56
还有更多的区域要报告吗?
名词
Polly Clitch的总投票数为48
Ernest Truble的总投票数为56
Polly Clitch的总票数百分比为0.0%
Ernest Truble的总票数百分比为0.0%