javascript pow 参数 - Armstrong Numbers
javascript pow parameters - Armstrong Numbers
正在尝试编写 armstrong 函数。我使用 chrome 进行调试,发现当我尝试分配 pow 的结果时它会在 val1 上爆炸。我尝试同时使用 array[element] 和 array[element].value 但它也不喜欢。
//Armstrong numbers
function armstrong() {
var numberStr = document.getElementById('inputNumber').value;
var numberInt = parseInt(numberStr);
var arrayOfNum = numberStr.split('');
var val1, val2, val3, total = 0;
var displayResult = document.getElementById('displayResult');
for (i = 0; i < arrayOfNum.length; i++) {
arrayOfNum[i] = parseInt(arrayOfNum[i]);
}
if (arrayOfNum.length === 3) {
val1 = Math.pow(arrayOfNum[0], 3);
val2 = Math.pow(arrayOfNum[1], 3);
val3 = Math.pow(arrayOfNum[2], 3);
total = val1 + val2 + val3;
if (total === numberInt) {
//display msg that number is armstrong
displayResult.innerHTML = "Your number " + numberInt + " is an Armstrong Number.";
} else {
//display msg that not armstrong
displayResult.innerHTML = "Your number " + numberInt + " is NOT an Armstrong Number.";
}
} else {
// display msg to enter a 3 digit number
displayResult.innerHTML = "You must enter a 3 digit number.";
}
}
你正在使用 pow .in javascript 它的 Math.pow()
将您的代码替换为此
val1 = Math.pow(arrayOfNum[0].value, 3);
val2 = Math.pow(arrayOfNum[1].value, 3);
val3 = Math.pow(arrayOfNum[2].value, 3);
正在尝试编写 armstrong 函数。我使用 chrome 进行调试,发现当我尝试分配 pow 的结果时它会在 val1 上爆炸。我尝试同时使用 array[element] 和 array[element].value 但它也不喜欢。
//Armstrong numbers
function armstrong() {
var numberStr = document.getElementById('inputNumber').value;
var numberInt = parseInt(numberStr);
var arrayOfNum = numberStr.split('');
var val1, val2, val3, total = 0;
var displayResult = document.getElementById('displayResult');
for (i = 0; i < arrayOfNum.length; i++) {
arrayOfNum[i] = parseInt(arrayOfNum[i]);
}
if (arrayOfNum.length === 3) {
val1 = Math.pow(arrayOfNum[0], 3);
val2 = Math.pow(arrayOfNum[1], 3);
val3 = Math.pow(arrayOfNum[2], 3);
total = val1 + val2 + val3;
if (total === numberInt) {
//display msg that number is armstrong
displayResult.innerHTML = "Your number " + numberInt + " is an Armstrong Number.";
} else {
//display msg that not armstrong
displayResult.innerHTML = "Your number " + numberInt + " is NOT an Armstrong Number.";
}
} else {
// display msg to enter a 3 digit number
displayResult.innerHTML = "You must enter a 3 digit number.";
}
}
你正在使用 pow .in javascript 它的 Math.pow() 将您的代码替换为此
val1 = Math.pow(arrayOfNum[0].value, 3);
val2 = Math.pow(arrayOfNum[1].value, 3);
val3 = Math.pow(arrayOfNum[2].value, 3);