如何使用多次操作(如谐波和)填充数组:Harmonic = 1 + 1/2 + 1/3 + 1/4 ....... + 1 / n 我的不完整版本看起来像这样:
public static void main(String[] args) {
int x=1, harmonic=0, y=2;
int[] n;
n = new int[];
// for populating the array ?!?!?!
do {n = {x/y}}
y++;
while (y<=500);
//for the sum for loop will do...
for (int z=0; z<=n.length; z++){
harmonic += n[z];
}
System.out.println("Harmonic sum is: " + harmonic);
}
答案 0 :(得分:1)
2件事......你应该使用双数据类型,因为你不需要截断值,你应该使用那些集合而不是数组。
public static void main(String[] args) {
double x = 1, harmonic = 0, y = 2;
List<Double> arc = new ArrayList<>();
do {
arc.add(x / y);
y++;
} while (y <= 500);
for (Double double1 : arc) {
harmonic += double1;
}
System.out.println("Harmonic sum is: " + harmonic);
}
输出结果如下:
谐波总和为:5.792823429990519
使用流:
double streamedHarmonic = arc.stream().mapToDouble(Double::doubleValue).sum();