Java for 循环(数字之和 + 总数)

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

Java for loop (sum of numbers + total)

javaloopsfor-loopsum

提问by user2722931

I'm bit lost here. I have a forloop which increases a value, something like this:

我有点迷失在这里。我有一个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;
    }

This works fine, but I need sum of all numbers from loop as total:

这工作正常,但我需要循环中所有数字的总和:

loop: 10,20,30,40,50,70,90,120....
total:10,30,60,100,150,220,310,430...

I tried:

我试过:

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

But I get strange sums. So I need loop which increase numbers and sum of all those numbers. I hope this makes sense. Thanks.

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

回答by Louis

what you want to do is something along the lines of

你想做的是类似的事情

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

回答by Jonah

I might be misunderstanding you here but I believe you want something like this

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

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;

        }
        }
    }
 }

回答by LogronJ

declare a total variable then store the tota int total =0;

声明一个total变量然后存储tota int total =0;

total += nu01;

总计 += nu01;