我有这个金额:
显然,我必须根据 N
得出其总和。我需要用三种不同的方式来做到这一点。
首先是for
循环:
function lab(n) {
var S = 0;
let VS
if (n == 0) {
VS = 0;
return 0;
}
if (n == 1) {
VS = 4;
return Math.pow(3 / 5, 1);
} else {
for (let i = 0; i < n; i++) { //
S += 1 / n * Math.pow(3 / 5, n);
t = 4 * n;
}
return S;
}
}
第二个是递归:
function lab(n) {
let vs = 0;
if (n <= 1)
return 0;
else {
vs += 4 * n // vs is how many actions it takes to make this calculation. I’m sure in for loop this is right, but I’m not sure about the recursion approach
return lab(n - 1) + 1 / n * Math.pow(3 / 5, n)
}
}
第三种方法是使用递归,条件是为了获得 S(n),我需要使用 S(n-1)。
我被困在这个问题上。
此外,我从第一个和第二个函数中使用相同的 N
得到不同的总和。
最佳答案
不知道你要什么。
如果您需要递归函数,请查看以下内容:
function summation(n, sum = 0) {
if (n <= 0) {
return sum;
}
sum += (1/n) * Math.pow(3/5, n);
return summation(n - 1, sum);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
另一种不传递 sum 作为参数的递归方法:
function summation(n) {
if (n <= 0) {
return 0;
}
return ((1/n) * Math.pow(3/5, n)) + summation(n - 1);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
此外,对于循环方法,以下内容就足够了
function summation(n) {
var sum = 0;
while (n > 0) {
sum += (1/n) * Math.pow(3/5, n);
n -= 1;
}
return sum;
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
关于javascript - 使用递归获取序列之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758408/