在Java中,在for循环中将一个数字乘以n个值
我有: 我需要创建一个for循环,该循环获取工资x贡献的总和,如下所示: 工资x供款1=500x0.1 工资x供款2=500x0.2 ……等等 这是我班的一种方法:在Java中,在for循环中将一个数字乘以n个值,java,for-loop,multiplication,Java,For Loop,Multiplication,我有: 我需要创建一个for循环,该循环获取工资x贡献的总和,如下所示: 工资x供款1=500x0.1 工资x供款2=500x0.2 ……等等 这是我班的一种方法: salary = 2000; n= salary/200 = 10 //number of loops; contribution = 0.1, 0.2, 0.3, 0.4...; 公共静态双倍养老金分配(双倍工资){ 双n=工资/200; 整数n_round=(整数)数学层(n); int start=1; List n_Li
salary = 2000;
n= salary/200 = 10 //number of loops;
contribution = 0.1, 0.2, 0.3, 0.4...;
公共静态双倍养老金分配(双倍工资){
双n=工资/200;
整数n_round=(整数)数学层(n);
int start=1;
List n_List=IntStream.rangeClosed(开始,n_轮)
.boxed().collect(collector.toList());
双计数器=0.1;
对于(int i=0;i
谢谢 您可以使用此循环:
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<[循环次数];i++){
结果乘法=(工资*计数器)
求和=求和+结果乘法
计数器=计数器+0.1
}
回报金额;
您将从乘法求和得到所有结果。idk为什么您需要一个列表,但这将为您提供列表中每个n的乘法之和,您需要计算salaryn0.1并求和所有。 这可以在一个流中完成:
for(int i = 0;i < [times to loop];i++){
resultofmultiplication = (salary*counter)
sum = sum + resultofmultiplication
counter = counter + 0.1
}
return sum;
也许我认为列表是更好的选择,因为我习惯于用Python编程,而且在Java中非常新手。在for循环条件中缺少一个右括号。这很有效!谢谢for语句末尾缺少一个括号。
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();
}