由于某些原因,当我将数组传递给方法时,平均值被填充错误,我获得了非常低的百分比。几乎可以看出,由于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;
}
} // class
答案 0 :(得分:1)
旧问题,您使用整数算术total / nums.length
并返回int
值。您稍后将其分配给float
,但该值已被截断。
在分部之前,只需将其中一个值更改为float
,例如。 ((float) total) / num
答案 1 :(得分:1)
您正在计算5个数字的平均值,但您只设置了2个。因此,如果您的阵列中的所有镜头都显示如下:10, 10, 0, 0, 0
,平均值将为4。
答案 2 :(得分:0)
其中,你的表达
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;