java中的求和函数

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

summation function in java

javasum

提问by tawheed

I am getting strange behavior with this basic piece of java code

我对这段基本的 Java 代码产生了奇怪的行为

  public class Sigma {
       public static void main(String[] args) {
           int sum = sigma(3);
           System.out.println(sum);
       }

       public static int sigma(int n){
           int sum = 0;
           for (int i = 0; i <= n; i++) {
               sum += 1;
           }
           return sum;
       }
   }

The expected output is 6, however when I run the code I get 4

预期的输出是6,但是当我运行代码时,我得到4

采纳答案by Algorithmist

This is wrong, you should change sum += 1;to sum += i;

这是错误的,您应该更改sum += 1;sum += i;

And if you are doing an AP summation from 1 to N better use directly the formula:

如果你正在做从 1 到 N 的 AP 求和,最好直接使用公式:

(n*(n+1))/2

(n*(n+1))/2

回答by ihsan kocak

You should change the code as sum+=1to sum+=i;

你应该将代码修改sum+=1,以sum+=i;