Java:计算循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7361636/
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-10-30 19:40:00  来源:igfitidea点击:

Java: Calculate for loop

javafor-loop

提问by Michael

I've now googled around and tried various methods myself without any success. So to the problem, I've got this loop, I type in a number "n" ex. 10. Then the program counts from 1 to 10. This is the loop I'm using.

我现在已经在谷歌上搜索并尝试了各种方法,但没有任何成功。所以对于这个问题,我有这个循环,我输入一个数字“n”ex。10. 然后程序从 1 数到 10。这是我使用的循环。

n = Keyboard.readInt();
for(int e = 1; e <=n; e++)          
System.out.println(e);  

That works fine, but now I want to calculate the numbers that has been shown in loop so..It would be 1+2+3+4+5+6+7+8+9+10 (If 'n' was chosen as number 10) and it should give the calculation of that so it would say 1+2+3+4+5+6+7+8+9+10 = 55.

效果很好,但现在我想计算循环中显示的数字,所以..它会是 1+2+3+4+5+6+7+8+9+10(如果选择了“n”作为数字 10),它应该给出它的计算,所以它会说 1+2+3+4+5+6+7+8+9+10 = 55。

Would be great if anyone here could help me.

如果这里有人可以帮助我,那就太好了。

Thanks in advance,

提前致谢,

Michael.

迈克尔。

回答by NPE

You could do it the hard way or the easy way:

你可以用困难的方法或简单的方法来做:

  1. The hard way:Keep a running sum and add to it inside the loop.

  2. The easy way:Notice that the sum you're looking for equals n*(n+1)/2(which is easy to prove).

  1. 困难的方法:保持运行总和并在循环内添加到它。

  2. 简单的方法:请注意,您正在寻找的总和等于n*(n+1)/2(这很容易证明)。

回答by Brett Walker

StringBuilder buffer = new StringBuilder();
int n = Keyboard.readInt();
int sum = 0;

for ( int e = 1; e <=n; e++ )
{
  buffer.append( "+ " + e );
  sum += e;
}

System.out.println( buffer.substring( 2 ) + " = " + sum ); 

回答by RoflcoptrException

Do it like that:

这样做:

   public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        for(int e = 1; e <=n; e++)          
            sum = sum + e;
        System.out.println(sum);
    }

回答by Daniel

int sum = 0;

for(int e = 1; e <=n; e++)
{
    sum += e;
}

System.out.println(sum);

回答by Garrett Hall

Use another variable to accumulate the results.

使用另一个变量来累积结果。

回答by Bohemian

I feel like spoon-feeding, so here's the code:

我觉得像用勺子喂食,所以这是代码:

public static void main(String args[]) {
    int n = Keyboard.readInt();
    int total = 0;
    for (int i = 1; i <= n; i++)
        total += i;
    System.out.println(total);
}

回答by Mike C

Try this:

试试这个:

n = Keyboard.readInt();
int total = 0;
StringBuilder arith = new StringBuilder();

for(int e = 1; e <=n; e++) { 
   total += e;
   arith.append(e + (e < n? "+" : ""));
}

arith.append("=" + total);
System.out.println(arith.toString());