gpt4 book ai didi

javascript - 尝试使用 getElementById 在 Javascript 中打印正确答案

转载 作者:行者123 更新时间:2023-11-28 18:23:26 24 4
gpt4 key购买 nike

我试图确定一个数字是否是完美数字,但无法正确打印。数字 6、496、8128 是完美数字,但当我输入这些数字时,它一直从 var res2 而不是 var res1 打印。这是什么问题,有人可以帮忙吗?

function perfectNo(number) {
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}

if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>

最佳答案

尝试使用:

var number = document.getElementById("num").value;

像这样:

function perfectNo() {
var number = document.getElementById("num").value;
console.log(number);
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}

if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>

关于javascript - 尝试使用 getElementById 在 Javascript 中打印正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com