我对Java很新,并且一直在研究数组。任务是:
到目前为止我的代码:(请记住,它非常粗糙,我最后还是有点失落。) 所有我要求的是有人解释/帮助如何找到50 + - 平均值,并在数组中搜索用户输入
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] nums = new int[100];
for (int i = 0; i < nums.length; i++){
nums[i] =(int) (Math.random()*1000);
}
for (int i = 0; i < nums.length; i++){
if (i % 20 == 0){
System.out.println("\n");
}
System.out.print(nums[i] + " ");
}
int sum = 0;
for(int i = 0; i< nums.length; i++){
sum += nums[i];
}
int average;
average = sum/(nums.length);
System.out.println("\n\nThe average equals: "+ average);
int fifty = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= average - 50 && nums[i] >= average + 50){
fifty++;
}
}
System.out.print("Number of values within 50 of the average: " + fifty);
int usrVal;
System.out.println("\nEnter a value to test: ");
usrVal = in.nextInt();
}
}
答案 0 :(得分:0)
所以你知道你的平均值是什么
然后循环遍历您的数组并将每个数字与平均值进行比较
if (Math.abs (nums[i] - average) < 50) {
System.out.println (nums[i]);
// or count it or whatever
}