arrays - wrong results from simple java method -
this question has answer here:
i'm trying write program asks size of array of integers, values of array, , finds average of positive integers , prints it. when run it, wrong results. haven't identified on wrong results depends example if enter following input: "array size: 4, array values: 1, 2, -5, 5" average of "2.0"
here's code:
import java.util.scanner; public class mitra { private static scanner user_input; double avg (int[] arr, int size) { int sum = 0; int numbers = 0; (int i=0; i<size;i++) { if (arr[i]>0) { sum = sum+arr[i]; numbers++; } else{ continue; } } double average = sum/numbers; return average; } public static void main(string[] args) { user_input = new scanner (system.in); system.out.println("enter array length"); int alength = user_input.nextint(); int[] array_1 = new int[alength]; (int i=0; i<alength;i++) { system.out.println("enter array value "+i); array_1[i] = user_input.nextint(); } mitra obj = new mitra(); double result = obj.avg(array_1, alength); system.out.println("the average of positive numbers of array "+result); } }
change
double average = sum/numbers;
to
double average = (double)sum/numbers;
to force floating point division.
otherwise, int division (which operation takes place when dividing 2 variables of int type) give 2 when dividing 8/3 (as in example).
Comments
Post a Comment