1

So guys this is my code. the code runs fine but I don't get the proper average. Could someone please fix it.

import java.util.Scanner;
public class test {
    public static double Avg(int amt, int num) {
     int tot = 0;
     tot = tot + num;
     int average = tot/amt;
     return average;
public static void main(String[] args) {
    double average_ICT_01 = 0;
    Scanner sc = new Scanner(System.in);
    ArrayList<Integer> ICT_01 = new ArrayList<Integer>();
    for (int i=0; i<3; i++) {
        int num = sc.nextInt();
        ICT_01.add(num);
    }
     int length01 = ICT_01.size();
    for (int c=0; c<3; c++) {
        int num1 = ICT_01.get(c);
        average_ICT_01 = Avg(length01,num1);
    }

    System.out.println(average_ICT_01);
}      
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Damsara Perera
  • 161
  • 2
  • 13
  • 1
    What is input and what is expected out put.. What is your algorithm.. I feel like int tot = 0; is the problem (at first glance, it has to be outside of your method, i might be wrong because you haven't method your algorithm) – RamPrakash Nov 30 '17 at 22:00
  • Possible duplicate of [Dividing two integers to a double in java](https://stackoverflow.com/questions/19090526/dividing-two-integers-to-a-double-in-java) – Jacob G. Nov 30 '17 at 22:12

1 Answers1

0

The arithmetic average of n numbers is their sum divided by n. So a method for calculating the average of all the numbers in a vector should be:

public static double avg(List<int> vec){

    //Sum all numbers
    long sum = 0;


    for(int i=0;i<vec.size();i++){
        sum = sum + vec.get(i);
    }

    //Divide by the number of numbers
    double avg = sum/vec.size();

    //Return the average
    return avg;    
}