【问题标题】:Java for loop (sum of numbers + total)Java for 循环(数字总和 + 总数)
【发布时间】:2014-11-03 17:56:56
【问题描述】:

我有点迷路了。我有一个for 循环,它增加了一个值,如下所示:

int nu01 = 10000;
int level = 0;
int increase = 35000;

for (int i = 0; i < 100; i++) {
    nu01 = nu01 + increase;
    level++;
    System.out.println(nu01);

    if (level > 50) {
        increase = 45000;
    }

这很好用,但我需要循环中所有数字的总和:

循环:10,20,30,40,50,70,90,120.... 总计:10,30,60,100,150,220,310,430...

我试过了:

int total;
total=nu01 + nu01; //or  nu01 + nu01 + increase;

但我得到了奇怪的数字。所以我需要循环来增加数字和所有这些数字的总和。我希望这是有道理的。谢谢。

【问题讨论】:

    标签: java loops for-loop sum


    【解决方案1】:

    你想要做的事情类似于

    int total = 0;
    ...
    //beginning of your for loop
    total = total + nu01; // alternatively you could do total += nu01;
    

    【讨论】:

      【解决方案2】:

      我可能在这里误解了你,但我相信你想要这样的东西

      public class forLoops{
      
          public static void main(String args[]){
      
              //Initialisation
              int level = 0;
              int increase = 35000;
              int total = 10000;
      
              //For Loop
              for(int i = 0; i < 100; i++){
      
                  total += increase; //Same as total = total + increase;
                  level++;
                  System.out.println(total);
      
              if(level >= 50){
      
                  increase = 45000;
      
              }
              }
          }
       }
      

      【讨论】:

        【解决方案3】:

        声明一个总变量,然后存储总和 整数=0;

        总计 += nu01;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-03
          • 2018-08-08
          • 2021-05-18
          • 1970-01-01
          • 1970-01-01
          • 2023-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多