英文:
Multiply a number by n values in a for loop in Java
问题
我有:
salary = 2000;
n = salary / 200 = 10 // 循环次数;
contribution = 0.1, 0.2, 0.3, 0.4...;
我需要创建一个 for 循环,计算工资 x 缴纳比例的总和,如下所示:
工资 x 缴纳比例1 = 500x0.1
工资 x 缴纳比例2 = 500x0.2
...等等...
这是我的类中的一个方法:
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;
// 需要所有 (salary*counter) 值的总和
return n_round;
}
谢谢!
英文:
I have:
salary = 2000;
n= salary/200 = 10 //number of loops;
contribution = 0.1, 0.2, 0.3, 0.4...;
I need to make a for loop that gets the sum of salary x contribution as:
salary x contribution1 = 500x0.1
salary x contribution2 = 500x0.2
...etc...
this is a method of my 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;
}
Thanks!
答案1
得分: 0
你可以使用这个循环:
for(int i = 0; i < [循环次数]; i++){
结果乘积 = (工资*计数器)
总和 = 总和 + 结果乘积
计数器 = 计数器 + 0.1
}
返回 总和;
你将得到所有乘法运算的结果总和。不知道为什么你需要一个列表,但这将给你乘法结果的总和。
英文:
you can use this loop:
for(int i = 0;i < [times to loop];i++){
resultofmultiplication = (salary*counter)
sum = sum + resultofmultiplication
counter = counter + 0.1
}
return sum;
you will get all the results from the multiplications summed. idk why you need a list but this will give you the sum of the multiplications
答案2
得分: 0
对于列表中的每个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();
}
英文:
For each n in the list you need to calculate salaryn0.1 and sum all.
This can be done in one stream:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论