[英]Passing array through average method, resulting in low percent
由於某些原因,當我將數組傳遞給方法時,平均值被填充錯誤,我獲得了非常低的百分比。 幾乎可以看出,由於Array shotsMade只記錄制作鏡頭的整數,而不是錯過它不計算正確的基礎。
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//主要
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//類
舊問題,您使用整數算術total / nums.length
並返回一個int
值。 您稍后將其分配給float
,但該值已被截斷。
只需將其中一個值更改為在除法之前 float
,即vg ((float) total) / num
您正在計算5個號碼的avarage但只設置了2所以,如果所有的出手打你的陣列將是這樣的: 10, 10, 0, 0, 0
和avarage將是4。
其中,你的表達
float f = (total / nums.length);
會產生不准確的結果。
total
和nums.length
都是整數,整數之間的任何操作總是產生整數。
示例:如果total = 10且nums.length = 3,則您希望結果為3.333 ...但實際上結果只是3.只有在此之后才將其轉換為浮點數,結果為3.0。
要獲得所需的結果,您需要在分割之前將兩個整數轉換為浮點數:
float f = (float) total / (float) nums.length;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.