HOW COME THIS PROGRAM WON\'T GIVE ME BACK THE PERCENTAGE OF THE EVEN INTEGERS IN
ID: 3840170 • Letter: H
Question
HOW COME THIS PROGRAM WON'T GIVE ME BACK THE PERCENTAGE OF THE EVEN INTEGERS IN THE ARRAY?
CAN SOMEONE HELP FIX IT???
public class evenPercent{
public static void main(String[] args) {
double [ ] a = {3, 4, 5, 7, 8};
arraySum(a);
}
public static void arraySum(double[ ] a){
int sum = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
sum++;
}
}
double percent = (sum)/(a.length);
System.out.println(percent + "% of your values are even");
}
}
Explanation / Answer
The issue oin your program was that, you were trying to divide int by int and your precision was getting lost because of int/int. i.e. 2/5 in int is 0 not 0.4 (because 2/5 when casted to int will lose precision.)
Secondly, you are not multiplying the value after dividing to 100, as percentage is division multiplied by 100.
So we need to make two improvements. First to cast it to double and second is to multiply it with 100.
Below is your correct program. I have highlighted the statement to bold which I have changed.
public class evenPercent {
public static void main(String[] args) {
double[] a = { 3, 4, 5, 7, 8 };
arraySum(a);
}
public static void arraySum(double[] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
sum++;
}
}
double percent = (double)sum *100/ (a.length);
System.out.println(percent + "% of your values are even");
}
}
Sample Run: -
40.0% of your values are even