Java While 循环数求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20043596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:37:30  来源:igfitidea点击:

While loop numbers sum

javawhile-loop

提问by Jalmari

I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:

我需要有关如何计算 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;
        }
    }
}

How do I make it only print the last sum? If I try to trick the equation it just hangs.

如何让它只打印最后一笔?如果我试图欺骗等式,它就会挂起。

回答by Maroun

Use another variable instead of iwhich is the loop variable:

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

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

Now sumwill contain the desired output. In the previous version, you didn't really loop on all values of ifrom 1 to 101.

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

回答by Jean B

Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.

请尝试以下操作。稍微移动值以确保加起来为 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);
    }

}

回答by vangelion

Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.

您的总和 (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);
}

Alternatively, use the Gauss sum: n(n+1)/2

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

So, the end sum is 100(101)/2 = 5050

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

回答by user3003994

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

回答by Tushar Thakur

First either change your sum variable or index variable

首先更改您的总和变量或索引变量

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