繁体   English   中英

如何使用循环编写将 1 加到 n 的 function

[英]How to use a loop to write a function that adds 1 through n

我必须想出一个代码,如果 int 输入 n 小于 2,则返回 0,如果 n 大于 1,则返回整数 1 到 n 的总和。例如:如果 n 为 4,则返回 1+ 2+3+4

这是我到目前为止的代码,由于某种原因,它总是返回比我运行它时应该返回的更多:

    public static int sumton(int n){
        if (n<2){
            return 0;
        }
        int result=0;
        int i=1;
        while (i<=n){
            i=i+1;
            result=result+i;
            System.out.println(i);
        }
        return result;
}

使用 for 循环而不是 while 循环。

 public static int sumton(int n){
    if (n<2){
        return 0;
    }
    int result=0;
    
    for(int i=1; i<=n; i++)
    {
      result = result+i;
      System.out.println(i);
    }
    return result;
}

在 While 循环中,它应该是这样的:

  while (i<=n){
        result=result+i;
         i=i+1; //i++
        System.out.println(i);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM