如何使用for循环将数字从1添加到N?

时间:2017-12-27 06:18:31

标签: javascript

这是我目前的代码,但它不起作用!它的问题是什么?

它应该将所有数字从1添加到base_number,但代码不起作用。

function start(){
    var base_number = readInt("What is the base number? ");
    function adding();
}

function adding(){
    var sum = 0;
    for (var i = 1; i < base_number + 1; i++){
        sum += i;
    }
    return sum;
    println(sum);
}

3 个答案:

答案 0 :(得分:1)

function start(){
    var N =  Number(prompt("What is the base number? "));
    return  adding(N);
 }

function adding(N){
   return (N * (N + 1)) / 2;
}
console.log(start());

答案 1 :(得分:0)

println&amp; readInt不是javascript关键字。此外,在调用函数adding时,无需在此之前添加关键字function

var start = function() {
  var base_number = prompt("What is the base number? ");
  return adding(parseInt(base_number, 10));
};

function adding(base_number) {
  var sum = 0;
  for (var i = 1; i < base_number + 1; i++) {
    sum += i;
  }
  return sum;
}
console.log(start())

答案 2 :(得分:-1)

您需要将base_number传递给adding()函数

function start(){
        // read or declare base number 
        adding(base_number);
    }

    function adding(base_number){
        var sum = 0;
        for (var i = 1; i < base_number + 1; i++){
            sum += i;
        }
        console.log(sum);
        return sum;
    }