【问题标题】:While loop numbers sumWhile 循环数总和
【发布时间】:2013-11-18 08:54:22
【问题描述】:

我需要有关如何计算 while 循环打印的数字总和的帮助。我必须使用 while 循环获得数字 1 到 100 并一起计算所有这些数字。比如 1+2+3...+98+99+100。我可以得到数字,但不能一起计算它们。这是我的代码:

public class Loops {
    public static void main(String[] args) throws Exception {
        int i = 1;
        while (i < 101) {
           System.out.print(i);
           i = i + 1;
        }
    }
}

如何让它只打印最后一个总和?如果我试图欺骗方程式,它就会挂起。

【问题讨论】:

  • 您是在问如何声明另一个变量并为其添加i 的值?

标签: java while-loop


【解决方案1】:

使用另一个变量而不是循环变量i

int i   = 1;
int sum = 0;
while (i < 101) {
  sum += i;
  i++;
}

现在sum 将包含所需的输出。在以前的版本中,您并没有真正循环 i 从 1 到 101 的所有值。

【讨论】:

    【解决方案2】:

    首先要么改变你的总和变量或索引变量

    public class Loops {
     public static void main(String[] args) {
      int sum = 0;
      int i = 1;
      while (i < 101) {
       sum = sum + i;
       ++i;
      }
      System.out.println(sum);
    }
    

    【讨论】:

    • 很好地计算索引++,然后添加总和并打印它
    【解决方案3】:

    您的总和 (i) 也是您的索引。因此,每次添加时,都会跳过要添加的数字。

    public class Loops {
     public static void main(String[] args) {
      int sum = 0;
      int i = 1;
      while (i < 101) {
       //System.out.print(i);
       sum = sum + i;
       ++i;
      }
      System.out.println(sum);
    }
    

    或者,使用高斯和:n(n+1)/2

    所以,最终总和是 100(101)/2 = 5050

    【讨论】:

      【解决方案4】:

      试试下面的。稍微移动了一些值,以确保总和为 100 并始终显示总和。

      public static void main(String[] args) throws Exception {
      
          int i = 1;
          long tot = 1;
      
          while (i < 100) {   
             i += 1;
             tot += i;
             System.out.print("Number :" + i + "  ,sum="+tot);
          }
      
      }
      

      【讨论】:

        【解决方案5】:
        public class Loops {
          public static void main(String[] args) throws Exception {
            int i = 1;
            int sum = 0;
            while (i < 101) {
               sum = i + 1;
            }
            System.out.print(sum);
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-06-25
          • 2019-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-28
          • 1970-01-01
          • 2014-10-16
          • 1970-01-01
          相关资源
          最近更新 更多