在 Java 的 for 循环中将一个数字乘以 n 个值

Multiply a number by n values in a for loop in Java

我有:

salary = 2000;
n= salary/200 = 10 //number of loops;
contribution = 0.1, 0.2, 0.3, 0.4...;

我需要做一个 for 循环来获取工资 x 贡献的总和:

工资x贡献1 = 500x0.1 工资 x 贡献2 = 500x0.2 ...等等...

这是我的方法 class:


public static double pensionContribution(double salary) {
        
        
    double n = salary/200;
    int n_round = (int) Math.floor(n);
        
    int start = 1;
    List<Integer> n_list = IntStream.rangeClosed(start, n_round)
                .boxed().collect(Collectors.toList());
        
        
    double counter = 0.1;
        
    for (int i = 0; i < n_list.size(); i++) {
           System.out.println(n_list.get((int) (salary*counter)));
                 
    }
        counter = counter + 0.1;
        //need the sum of all values of (salary*counter)
        
    return n_round;
            
    }

谢谢!

你可以使用这个循环:

for(int i = 0;i < [times to loop];i++){

     resultofmultiplication = (salary*counter)
     sum = sum + resultofmultiplication
     counter = counter + 0.1

}
return sum;

您将得到乘法求和的所有结果。不知道为什么你需要一个列表,但这会给你乘法的总和

对于列表中的每个 n,您需要计算薪水n0.1 并求和。 这可以在一个流中完成:

public static double pensionContribution(double salary) {
    double n = salary/200;
    int n_round = (int) Math.floor(n);
    return IntStream.rangeClosed(1, n_round).mapToDouble(i->salary*i*0.1).sum();
}