求和数组值java

时间:2011-07-03 10:59:13

标签: java math

我正在喂一个长度为8的数组,如果试验为100则可能是形式为93 5 2 0 0 0 0 0,但无论我在数组中的值是多少,我只得到0.6。如果有人能看出我是否犯了一个很棒的愚蠢错误。我用for循环尝试了它但是一直保持0.6。

static void getMetric(int[]a, int trials){
    double metric = 0;
    int i =0;
    while(i<8){
        if(i==0){
            double x = (a[0] / trials) - (2 / 15);
            metric += Math.abs(x);
            i++;
        }
        else if(i>0 && i<7){
            double x = (a[i] / trials) - 0.1;
            metric += Math.abs(x);
            i++;
        }
        else{
            double x = (a[7] / trials) - (2 / 15);
            metric += Math.abs(x);
            System.out.println(""+metric);
            i++;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

使用整数除法(5/3 = 1; 2/15 = 0)。

因此,您应该a[0] / trials;

而不是a[0] / (double) trials

而不是2 / 15您应该2 / 15.0等。

答案 1 :(得分:2)

看起来你需要double - 除法而不是int - 除法。记住:

int a = 96;
int b = 100;
double c = a / b; //will be 0.0!

因此以下程序应该做同样的事情,但更正确,我认为(和更短):

static void getMetric(int[] a, int trials){
    double metric = Math.abs((((double)a[0]) / trials) - (2 / 15));

    for (int i = 1; i < 7; i++) {
        metric += Math.abs((((double)a[i]) / trials) - 0.1);
    }

    metric += Math.abs((((double)a[7]) / trials) - (2 / 15));

    System.out.println(""+metric);
}

而且那个更可靠,更健壮:

static void getMetric(int[] a, int trials){
    double metric = calcMetricDiff(a[0], trials, 2.0 / 15.0);

    for (int i = 1; i < a.length - 1; i++) {
        metric += calcMetricDiff(a[i], trials, 0.1);
    }   

    metric += calcMetricDiff(a[a.length-1], trials, 2.0 / 15.0);

    System.out.println(""+metric);
}   

private static double calcMetricDiff(double val, int trials, double diff) {
    return Math.abs((val / trials) - diff);
}