【问题标题】:Multiply a number by n values in a for loop in Java在Java的for循环中将一个数字乘以n个值
【发布时间】:2020-09-22 14:47:55
【问题描述】:

我有:

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 ...等等...

这是我班级的一个方法:


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;
            
    }

谢谢!

【问题讨论】:

    标签: java for-loop multiplication


    【解决方案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 语句的末尾少了一个括号。
    【解决方案2】:

    对于列表中的每个 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 2021-11-10
      相关资源
      最近更新 更多