如何使用JavaScript查找1到N之间的所有数字的总和 [英] How to find the sum of all numbers between 1 and N using JavaScript

查看:161
本文介绍了如何使用JavaScript查找1到N之间的所有数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种方法来使用JavaScript计算1到N之间所有数字的总和。以下是我到目前为止尝试的代码,但它似乎不起作用。

I'm trying to find a way to calculate the sum of all numbers between 1 to N using JavaScript. The following is the code I have tried so far but it doesn't seem to work.

function numberSum(N) {
  var total = 0;
    for(var i = 1; i <= N; i++){
      total += i;
    }
    return total;
}

我尝试在线使用jslint和其他验证工具来检查我是否可能错过了但是这似乎没有帮助我找到代码无法工作的原因。是否有一些我在上面遗漏的东西阻止脚本执行添加?

I have tried using jslint and other validators online to check if I might have missed something but that doesn't seem to help me find the reason for the code not working either. Is there something that I'm missing above that's preventing the script from executing the addition??

推荐答案

您的代码没问题。

保持简单:

var res = (n * (n+1)) / 2;

Wiki

这篇关于如何使用JavaScript查找1到N之间的所有数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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