[英]I'm trying to raise numbers to their consecutive powers and my code isn't working
https://codepen.io/aholston/pen/ZJbrjd https://codepen.io/aholston/pen/ZJbrjd
The codepen link has commented code as well as actual instructions in HTML codepen链接已注释了代码以及HTML中的实际说明
Otherwise.... what I ultimately have to do is write a function that takes two params(a and b) and takes all the numbers between those two params (ab) and put every number that can be added to the consecutive fowers and be equal to that number into a new array. 否则......我最终要做的是编写一个函数,该函数接受两个参数(a和b),并接受这两个参数之间的所有数字(ab),然后将可以加到连续fower上的每个数字放入等于那个数字到一个新的数组。 Ex: 89 = 8^1 + 9^2 = 89 or 135 = 1^1 + 3^2 + 5^3 = 135
例如:89 = 8 ^ 1 + 9 ^ 2 = 89或135 = 1 ^ 1 + 3 ^ 2 + 5 ^ 3 = 135
function sumDigPow(a, b) {
// Your code here
var numbers = [];
var checkNum = [];
var finalNum = [];
var total = 0;
for (var i = 1; i <= b; i++) {
if (i >= a && i <= b) {
numbers.push(i);
}
}
for (var x = 0; x < numbers.length; x++) {
var checkNum = numbers[x].toString().split('');
if (checkNum.length == 1) {
var together = parseInt(checkNum);
finalNum.push(together);
} else if (checkNum.length > 1) {
var together = checkNum.join('');
var togNumber = parseInt(together);
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
try this: 尝试这个:
function listnum(a, b) {
var finalNum = [];
for (var i = a; i <= b; i++) {
var x = i;
var y = i;
var tot = 0;
j = i.toString().length;
while (y) {
tot += Math.pow((y%10), j--);
y = Math.floor(y/10);
}
if (tot == x)
finalNum.push(i);
}
return finalNum;
}
console.log(listnum(1, 200));
Okay, after debugging this is what I learned. 好的,调试之后,这就是我学到的东西。
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
} }
Everytime this loop happened, I neglected to reset the 'total' variable back to 0. So I was never getting the right answer for my Math.pow() because my answer was always adding to the previous value of total. 每次发生此循环时,我都忽略了将“总计”变量重置为0。因此,对于我的Math.pow(),我从来没有得到正确的答案,因为我的答案总是与之前的total值相加。 In order to fix this, I added var total = 0;
为了解决这个问题,我添加了var total = 0; after i decided whether or not to push 'togNumber' into 'finalNum.'
在我决定是否将“ togNumber”推入“ finalNum”之后。 So my code looks like this..
所以我的代码看起来像这样。
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);}
}
var total = 0;
}
return finalNum;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.