【问题标题】:Java average method stuckJava平均方法卡住了
【发布时间】:2018-05-14 23:04:50
【问题描述】:

所以伙计们,这是我的代码。代码运行良好,但我没有得到正确的平均值。有人可以解决它。

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);
}      
}

【问题讨论】:

  • 什么是输入,什么是预期输出..你的算法是什么..我觉得 int tot = 0;是问题所在(乍一看,它必须在你的方法之外,我可能是错的,因为你没有方法你的算法)

标签: java arrays static double public


【解决方案1】:

n 个数字的算术平均值是它们的总和除以 n。所以计算向量中所有数字的平均值的方法应该是:

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;    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多