How to calculate the percentage of even numbers in an array?

I am starting, and here is the method I struggle with.

Write a method called percentEven that takes an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements {6, 2, 9, 11, 3}, then your method should return 40.0. If the array does not contain even elements or elements at all, return 0.0.

that's what i still have ...

public static double percentEven(int[]a){
    int count = 0;
    double percent = 0.0;
    if (a.length > 0){
        for ( int i = 0; i < a.length; i++){
            if ( a[i] % 2 == 0){
                count++;
            }
        }
            percent  =(count/a.length)*100.0;
    }
            return percent;
}

I keep returning 0.0 when the array contains a combination of even and odd elements, but works fine for all even arrays of elements or the entire odd array? I do not see where the problem is? thanks in advance.

+4
source share
4 answers

count/a.length 0, ints, . (double)count/a.length, .

:

percent = 100.0*count/a.length;
+8

@: , .

:

public class PercentEven {

    public static void main(String args[]){
        int count = 0;
        int[] a={2, 5, 9, 11, 0}; // this can be dynamic.I tried diff values 
        double percent = 0.0;
        if (a.length > 0){
            for ( int i = 0; i < a.length; i++){
                if ( a[i] % 2 == 0){
                    count++;
                }
            }
                percent  = (100*count/a.length);
        }
        System.out.println(percent);
    }
}
+1

For simple division, such as 2 * 100.0 / 5 = 40.0, the above logic will work fine, but think about the situation when we have 51 * 100.0 / 83, the output will be less readable, and it is always advisable to truncate the percentage of limited decimal digits.

Example:

int count = 51;
Double percent = 0.0;
int length = 83;
percent = count*100.0/length;

System.out.println(percent);

: 61.44578313253012

When you truncate it:

Double truncatedDouble = new BigDecimal(percent ).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(truncatedDouble);

: 61.446

+1
source
List<Integer> numbers = Arrays.asList(a);
int number = numbers.stream().filter(n->n%2==0).count();
int percent = number*100.0/numbers.size();

I did it in java 8

0
source

Source: https://habr.com/ru/post/1628083/


All Articles