简体   繁体   English

如何计算数组中偶数和奇数的平均值?

[英]How to calculate the average of even and odd numbers in an array?

As a class exercise I have to code using methods a program that: 作为课堂练习,我必须使用方法编写程序:

1) Calculates the average of even and odd numbers in an array. 1)计算数组中偶数和奇数的平均值。

I expect on using one method to find the average of even and odd numbers. 我期望使用一种方法来找到偶数和奇数的平均值。 However, I'm having trouble on returning the right average. 但是,我在返回正确的平均值时遇到了麻烦。 For example, if I enter only odd numbers I get an error, and vice versa. 例如,如果我仅输入奇数,则会出现错误,反之亦然。

This error: "java.lang.ArithmeticException: / zero" 错误:“ java.lang.ArithmeticException:/零”

Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for: 另外,如果可能的话,我想在编码其余要求的练习时获得一些帮助:

2) Print the highest and lowest number in the array 3) Allow the user to modify any of the numbers of the array 2)打印数组中的最高和最低数字3)允许用户修改数组中的任何数字

So far I have this code: 到目前为止,我有以下代码:

public static void main (String args[]){

    int x[] = new int[4];
    Scanner input = new Scanner(System.in);

    for(int i = 0; i < x.length ; i++){
        System.out.println("Enter a number: ");
        x[i] = input.nextInt();
    }


    System.out.println("Average of even numbers: " + getAverage(x));
    System.out.println("Average of odd numbers: " + getAverage(x));

 }

public static int getAverage(int a[]){
    int add_even = 0;
    int counter_even = 0;
    int average_even = 0;

    int add_odd = 0;
    int counter_odd = 0;
    int average_odd = 0;


    for(int i = 0; i < a.length; i++){
        if(a[i] % 2 == 0){
            add_even += a[i];
            counter_even++;
        }
        else if(a[i] % 2 == 1) {
            add_odd += a[i];
            counter_odd++;
        }

    }

    if (add_even % 2 == 1 && add_odd % 2 == 1){
    average_even = 0;
    average_odd = add_odd / counter_odd;

    return average_even;
   }
   else if (add_even % 2 == 0 && add_odd % 2 == 0){
    average_even = add_even / counter_even;
    average_odd = 0;

    return average_even;
    }
   else{

    average_even = 0;
    average_odd = add_odd / counter_odd;

    return average_odd;

    }


} 

Thank you! 谢谢!

You have a divide by zero error cropping up here. 您在这里出现零除错误。

else if (add_even % 2 == 0 && add_odd % 2 == 0){
    average_even = add_even / counter_even;
    average_odd = 0;
    return average_even;
}

0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. 0 % 2 == 0因此即使add_even为0(因此,counter_even也是如此),您仍在尝试使用它进行除法。 You'll need to account for that in your code by checking if counter_even is 0. 您需要通过检查counter_even是否为0来在代码中说明这一点。

else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){

1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int . 1)使用一种方法来获取偶数和奇数的平均值是不合适的,因为您只return一个int It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. 使用两种方法会更简单,但是如果您坚持使用一种方法,则可以像这样添加一个boolean作为参数来决定要执行的操作。 To handle the ArithmeticException just return 0 if there are no values. 要处理ArithmeticException只要没有值就return 0

public static int average(int[] n, boolean even) {
     int total = 0;
     int count = 0;
     for (int i = 0; i < n.length; i++) {
          if (even == (n % 2 == 0)) {
               total += n;
               count ++;
          }
     }
     if (count == 0)
          return 0;
     return total / count;

2)To check find the max and min value simply loop through the array like this 2)要检查找到最大值和最小值,只需像这样遍历数组

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

for (int i = 0; i < x.length; i++) {
     if (x[i] < min)
          min = x[i];
     if (x[i] > max)
          max = x[i];
}

3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this. 3)要允许用户修改数组,您可以打印这些值,并提示他们要更改的值,如下所示。

System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
     System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();

You can then run a method that changes the value of the array 然后,您可以运行更改数组值的方法

edit(x, index, value);

public static int edit(int[] n, int index, int value) {
     n[index] = value;
     return n;
}

Your get average looks more complicated then it needs to be. 得到的平均数看起来要复杂得多。

First off the getAverage(x) : 首先是getAverage(x)

System.out.println("Average of even numbers: " + getAverage(x));
    System.out.println("Average of odd numbers: " + getAverage(x));

will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even. 将会返回相同的值,因此,如果您想获取赔率或偶数的平均值,则该方法应要求一个布尔型arg来表示奇数或偶数。

In your method you should loop through all the numbers and check if it is even. 在您的方法中,您应该遍历所有数字并检查其是否为偶数。 If it is even and you are averaging evens add it to a "total" and add one to a counter. 如果是偶数,并且您是平均数,则将其添加到“总计”,然后将其添加到计数器。 At the end divide "total" by the counter and return the value. 最后,将“总计”除以计数器并返回值。 The average will most likely include a decimal value, so you should return a double or a float. 该平均值很可能包含一个十进制值,因此您应该返回一个double或float。

Example: 例:

public static double getAverage(int a[], boolean even){
  double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
    double counter = 0;
  for(int i = 0; i<a.length; i++){
    if(a[i] % 2 == 0 && even){//even
      counter++;
      total += a[i];
    }else{//odd
      counter++;
      total += a[i];
    }
  }
  if(total == 0){//Avoid dividing by 0.
    return 0; //You can also throw an exception instead of returning 0.
  }
  return total / counter; //Returns the average for even or odd numbers.
}

For the second part of your question you need to loop through the numbers and find the highest and lowest while looping. 对于问题的第二部分,您需要遍历数字并在遍历时找到最高和最低值。

Example: 例:

int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
  if(x[i] > highest){
    highest = x[i];
  }
  if(x[i] < lowest){
    lowest = x[i];
  }
  if(i == 0){
    highest = x[i];
    lowest = x[i];  
  }
}

I used JS for this task, you can just rewrite my code to Java language. 我使用JS完成此任务,您可以将我的代码重写为Java语言。

A number is divisible by 2 if the result of its division by 2 has no remainder or fractional component - in other terms if the result is an integer. 如果数字被2除的结果没有余数或小数部分,那么该数字可以被2整除;换句话说,如果结果是整数,则该数字可以被2整除。 Zero is an even number because when 0 is divided by 2, the resulting quotient turns out to also be 0 - an integer (as a whole number that can be written without a remainder, 0 classifies as an integer). 零是偶数,因为当0除以2时,所得商也将是0-整数(作为可以写而没有余数的整数,0分类为整数)。

 function compareEvenOddAverage(arr) { let even = 0, odd = 0, evenCounter = 0, oddCounter = 0, str = ''; for (let i = 0; i < arr.length; i++) { if (arr[i] % 2 === 0) { even += arr[i]; evenCounter++; } else { odd += arr[i]; oddCounter++; } } if (even / evenCounter > odd / oddCounter) { str += 'Average value of even numbers is greater'; } else if (even / evenCounter < odd / oddCounter) { str += 'Average value of odd numbers is greater'; } else { str += 'Average values are equal'; } return str; } console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5])); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM