好的,所以我已經研究了一段時間,我是第一次在 html 上制作回文程式,但是當我輸入 111 時,它說它不是回文,即使我使用 calc 完成了 while 回圈,它應該是相同的. 我通過顯示 em 和“輸入”= 111來檢查輸出。“溫度”= 0,因為它應該。“反轉” tho 等于無窮大笑和 idk y 任何幫助表示贊賞。
function Palindrome() {
let input = document.querySelector("#userInput").value;
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) lastDigit;
temp = (temp / 10);
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
}else {
document.querySelector("#answer").innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
uj5u.com熱心網友回復:
您正在執行浮點除法,因此temp在您進行多次迭代并獲得浮點下溢之前,它永遠不會超過 0。每次迭代后,它變成11.1,然后1.11,然后0.111,.0111等等。這是reversed每次乘以10,最終溢位到無窮大。
除法時對數字進行四舍五入,以便丟棄分數:
temp = Math.round(temp / 10);
function Palindrome(input) {
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) lastDigit;
temp = Math.round(temp / 10);
}
if (input == reversed) {
console.log(`This is a Palindrome ${input}`);
} else {
console.log(`This is not a Palindrome ${input} ${temp} ${reversed} `);
}
}
Palindrome(111);
Palindrome(123)
uj5u.com熱心網友回復:
正如 Barmar 在他關于百分比除法的回答中所解釋的那樣,嘗試擺脫它!
function Palindrome() {
let input = document.querySelector("#userInput").value;
//convert input to number
var temp = input;//or parseInt(input)
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = reversed * 10 lastDigit;
temp = Math.floor(temp / 10);//<-- to prevent Infinity
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
} else {
document.querySelector(
"#answer"
).innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
<input type="input" value="" id="userInput">
<input type="button" value="Is Palindrom" onclick="Palindrome()">
<div id='answer'></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359030.html
標籤:javascript html
上一篇:按找到的第一個分隔符拆分字串
下一篇:檢查div的顯示CSS
