[英]Why Am I Getting An NaN Error For My JavaScript Code Arithmetic Equation
我正在嘗試為一項任務創建一個婚禮宴會桌計划器應用程序,但是我的“table”變量出現了 NaN 錯誤,而我的 return 語句中的“guests”變量卻沒有。 圖片是我在我的網站上看到的,下面是腳本代碼。 我正在使用帶有 JavaScript 的 HTML 語言。 謝謝你的幫助!
function distribGuests() {
// Read the table value inputed by the user
var text = document.getElementById('tablesInputBox').value;
// Convert what the user typed from text into a number.
var t = (text);
// Read the guests value inputed by the user
var text = document.getElementById('guestsInputBox').value;
// Convert what the user typed from text into a number.
var g = (text);
// Formula for variable "a", the rounded down value of guests
var a = Math.floor (g / t);
// Formula for variable "b", the rounded up value of guests
var b = Math.round (g / t);
// Formula for variable "x", the end result for the first set of table distributions
var x = (g - b * t) / (a - b);
// Formula for variable "y", the end result for the second set of table distrubutions
var y = (t - x);
// Use string concatenation to produce statement for end result of wedding table distribution
var message = "There will be "+ x +" tables with "+ b +" guests and "+ y +" tables with "+ a +" guests";
// Display the message in the div that has the outputDiv
document.getElementById('outputMessage').innerHTML = message;
}
括號不會將字符串轉換為數字。
// Convert what the user typed from text into a number.
var t = (text);
應該:
// Convert what the user typed from text into a number.
var t = +text;
您也可以使用parseInt(text)
,但+text
對於您的用例實際上是相同的(稱為類型強制)。
(兩種方法的區別分析見這個問題)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.