[英]Java percentage calculation based on multiple inputs
我有點困惑如何根據輸入值計算百分比(例如:選擇團隊)
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
}
System.out.println(team1);
System.out.println(team2);
System.out.println(draw);
int total = team1 + team2 + draw;
System.out.println(total);
這將單獨打印和總計打印。 例如,如果所有值都從輸入中選取 2 次,我想打印:
“第一隊 = 33.3%,第二隊 = 33.3%,平局 = 33.3%”等等不同類型的選秀權。 謝謝
要獲得每個價格的百分比,您必須執行以下操作:
int persentageteam1 = team1*100/(team1+team2+team3);
其他人也一樣......
解釋:
你在這里做的是將你想要找到的價格與其他價格的總和相除,然后做這個 x100
你快到了。 現在,您只需要一個計數器來計算迭代次數,最后將 team1、team2 和 draw 的分數除以計數器的值,然后將它們乘以100.0
以獲得百分比分數。
演示:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
int count = -1;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
count++;
}
System.out.printf("Percentage score of team1: %.1f%n", (team1 * 100.0 / count));
System.out.printf("Percentage score of team2: %.1f%n", (team2 * 100.0 / count));
System.out.printf("Percentage score of draw: %.1f%n", (draw * 100.0 / count));
}
}
示例運行:
1 for Team one, 2 for Team two, 3 for draw, 9 for quit
1
2
3
3
2
1
9
Percentage score of team1: 33.3
Percentage score of team2: 33.3
Percentage score of draw: 33.3
一個數字的百分比是根據以下原則計算的(或者至少是我學校教的):比如說,你需要找出另一個數字的百分比,讓它是 firstNumber 和 secondNumber。 然后,firstNumber=100% 和 secondNumber=x。 由此我們得到比例:firstNumber/secondNumber = 100%/x,因此,x=(secondNumber*100)/firstNumber。 也就是說,在您的情況下, firstNumber 是所有球隊的選擇摘要,而 secondNumber - 您要確定的球隊百分比。 例如
//your code
int pickSummary=team1+team2+team3+draw;
int team1Percentage=team1*100/pickSummary;
System.out.println(team1Percentage);
//and so on
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.