简体   繁体   English

java,计算标准偏差。 卡在我的上一个代码中

[英]java, counting Standard Deviation. stuck in my last code

public int deviasi(){
    //sum
    int jumlah=0;
    for (int i=0; i<banyak; i++){
        jumlah = jumlah+nilai[i];
    }
    //mean
    int rata2;
    rata2=jumlah/banyak;

    //menghitung deviasi
    double deviasi = 0;
    for (int i=0;i<banyak;i++){
     deviasi += Math.pow(nilai[i] - rata2,2);
    }
    return

    Math.sqrt (deviasi/banyak);

}

i got error in my last code. 我在上一个代码中出错。 it told me the problem because of different data type between deviasi and banyak. 它告诉我这个问题,因为deviasi和banyak之间的数据类型不同。 but, i've changed the data type to make them have the same data type. 但是,我更改了数据类型以使它们具有相同的数据类型。 but the error warning still told me the problem because of different data type between deviasi and banyak. 但是由于deviasi和banyak之间的数据类型不同,错误警告仍然告诉我该问题。 i got stuck. 我被困。 T_T T_T

// Code returns 3.7549966711037173 public class Devs { //代码返回3.7549966711037173 public class Devs {

public static double deviasi(){

    //sum
    int jumlah= 0;
    int[] nilai = {4,7,6,3,9,12,11,12,12,15};
    int banyak = 10;


    for (int i=0; i<banyak; i++){
        jumlah += nilai[i];
    }

    //mean
    int rata2;
    rata2=jumlah/banyak;

    //menghitung deviasi
    double deviasi = 0;
    for (int i=0;i<banyak;i++){
     deviasi += Math.pow(nilai[i] - rata2,2);
    }

    return Math.sqrt (deviasi/banyak);

}

public static void main(String args[]) {


    System.out.println(deviasi());

}

} }

Like mentioned in comments you need to work with double as variable type 如注释中所述,您需要使用double作为变量类型

public class StandDev {

  public double standardDevioation(int[] numbers){
    int count = numbers.length;
    double sum = 0.0;
    for (int i = 0; i < count; i++){
      sum += numbers[i];
    }

    double mean = sum / count;

    double sumDiff = 0.0;
    for (int i = 0; i< count; i++){
      sumDiff += Math.pow(numbers[i] - mean,2);
    }

    return Math.sqrt (sumDiff/count);
  }

  public static void main(String[] args) {
    int[] numbers =  {-5, 1, 8, 7, 2};
    StandDev standDev = new StandDev();
    System.out.println(standDev.standardDevioation(numbers));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM