【发布时间】:2018-12-01 14:49:43
【问题描述】:
我正在尝试编写一个程序来计算加权中位数,但我遇到了一个无法解决的小问题。 要找到加权中位数,您必须将每个权重除以总和,然后将其与 0.5 进行比较,如果更大意味着找到的加权中位数则返回相应的 x 值。 这里是一个例子:
x = [3,4,6,10]
w = [1,2,3,5]
1/11 > 1/2 ? no
1/11+ 2/11 > 1/2 ? no
1/11+ 2/11 + 3/11 > 1/2 ? yes
然后返回 6,因为它对应于 3
这是我的尝试:
public static void main(String[] args) {
int[] x = new int[] {3,4,6,10};
int[] w = new int[] {1,2,3,5};
int sum = Arrays.stream(w).sum();//11
if ((w[0]/sum)>0.5){
System.out.print("The weighted meadin is " + x[0]);
}
else if ((w[0]/sum)+(w[1]/sum)>0.5){
System.out.print("The weighted meadin is " + x[1]);
}
else if ((w[0]/sum)+(w[1]/sum)+(w[2]/sum)>0.5){
System.out.print("The weighted meadin is " + x[2]);
}
else if ((w[0]/sum)+(w[1]/sum)+(w[2]/sum)+(w[3]/sum)>0.5){
System.out.print("The weighted meadin is " + x[3]);
}
else{
System.out.print("The weighted meadin not found");
}
}
这总是返回最后一个 else 语句。
【问题讨论】:
-
您在 w[0]/sum 等中使用整数除法,它始终为零。切换到浮动或双,开始。
-
谢谢!!我知道这是一个愚蠢的错误:(