i am beginner and here is the method I am struggling with.
Write a method called percentEven that accepts 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 contains no even elements or no elements at all, return 0.0.
here is what I have so far...
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 array contains a mix of even and odd elements but works fine for all even element array or all odd array? i can't see where the problem is? thanks in advance.
count/a.length
returns 0
since you are dividing two ints, and the second operand is larger than the first. Change it to (double)count/a.length
in order to perform floating point division.
Alternately, change the order of operations to :
percent = 100.0*count/a.length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With