如何计算从 0 到 n 的所有数字的总和? [英] How do I calculate the sum of all numbers from 0 to n?

查看:79
本文介绍了如何计算从 0 到 n 的所有数字的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用我的代码中看到的循环来计算从 0 到给定数字 (n) 的所有数字,但我似乎无法管理如何.

So I'm trying to calculate all the numbers from 0 to a given number (n) with a loop as seen in my code but I just can't seem to manage how.

public static int sumOfNumbers(int... params) {

     int sum = 0;

     for (int i : params) {
         sum = i;
     };

     return sum;
}      

推荐答案

您正在覆盖 sum,而不是添加它.您应该使用 += 运算符而不是 = 运算符:

You're overwriting sum, not adding to it. You should use the += operator instead of the = operator:

sum += i;

或者,您可以将此视为一个数学问题,并使用总和的公式等差数列:

Alternatively, you can treat this as a mathematical problem, and use the formula for the sum of an arithmetic progression:

public static int sumZeroToN(int n) {
    return n * (n + 1) / 2;
}

这篇关于如何计算从 0 到 n 的所有数字的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆