Python爬虫知识点总结:奥丁项目-基础知识4练习-总结(functions javascript exercises)

我被困在来自 Odin 项目的 Fundamentals 4 部分的 sumAll 练习中。我设法通过了我需要结果为 'ERROR' 的测试。但是,我无法找出正确的代码来通过其他测试。我哪里出错了?

这是练习:

const sumAll = require(’./sumAll’)
describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});

我的代码:

const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}
if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}
module.exports = sumAll
0

我以这种方式:

const sumAll = function (x, y) {
if (x > 0 && y > 0 && typeof x === 'number' && typeof y === 'number') {
    var valorx = x;
    var valory = y;
    var total = 0;
    if (x < y) {
        for (var i = valorx; i <= valory; i++) {
            total += i;
        }
        return total;
    } else if (x > y) {
        for (var i = valory; i <= valorx; i++) {
            total += i;
        }
        return total;
    }
} else {
    return 'ERROR'
 }
}
module.exports = sumAll
0

这对我来说是如何工作的

const sumAll = function (startN, endN) {
//create variable to store total sum
  let sum = 0;

检查输入参数是否在数字中:

  if (typeof startN != "number" || typeof endN != "number") return "ERROR";

检查输入数字是否大于 0:

  else if (startN < 0 || endN < 0) return "ERROR";

和最后一次检查是,如果最后一个数字大于第一个数字,那么初始数字将是最后一个数字,否则开始数字将是初始的:

  else if (startN < endN) {
    for (i = startN; i <= endN; i++) {
      sum += i;
    }
  } else {
    for (i = endN; i <= startN; i++) {
      sum += i;
    }
  }

然后返回总和:

  return sum;
};

你可以让所有这些在一个检查,但这是更可读。

0

我就是这样做的。很相似,但我避免使用 for 循环。

const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m 
}else{
    n1 = m
    n2 = n
}
return (n1+n2)*(n2/2)}
};

我首先检查输入是否有效,然后决定两个变量的值取决于哪个更大,最后计算总和。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(398)
Scratch编程课程总结:如何从头开始编程 (how to start programming)
上一篇
服务器挖矿:COM服务器是“服务器”吗 (com server)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(70条)