为什么我的JavaScript代码算术方程式出现NaN错误

时间:2019-02-23 01:53:25

标签: javascript html

enter image description here

我正在尝试为一项任务创建一个婚礼宴会桌计划程序应用程序,但是我的return语句中的“ table”变量而不是“ guests”变量出现NaN错误。图片是我在网站上得到的,下面是脚本代码。我正在使用HTML语言和JavaScript。感谢您的帮助!

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;
}

1 个答案:

答案 0 :(得分:0)

括号不能将字符串转换为数字。

  // 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对于您的用例实际上是相同的(称为类型强制)。

(有关这两种方法之间差异的分析,请参见this question