我一直得到NaN,我无法找到如何解决它

时间:2015-09-21 08:28:43

标签: javascript html nan

当它到达cost2时会发生。我认为问题可能在于尝试定义price2,其他一切正常。我是JavaScript的新手,所以我确定这是一个简单的错误,但任何帮助都会很棒!

<html>
    <body>
        <h1>Gas Mileage</h1><br></br>
    </body>
    <script type="text/javascript">
        var mpg, price1, distance, gallons, cost1, price2, cost2;

        mpg = prompt("Enter your car's miles per gallon");
        document.write("Your car gets "+mpg+" miles per gallon.");
        document.write("<br>");

        price1 = prompt("Enter the current cost of gas");
        document.write("Gas currently costs $"+price1+" per gallon.");
        document.write("<br>");

        distance = prompt("Enter the amount of miles you would like to travel");
        gallons = distance/mpg;
        cost1 = gallons*price1;
        document.write("To travel "+distance+" miles, it will cost you $"+cost1);
        document.write("<br>");

        price2 = (0.1+price1);
        cost2 = gallons*price2;
        document.write("But if gas were to cost 10 cents more per gallon, it would cost you $"+cost2);

    </script>
</html>

1 个答案:

答案 0 :(得分:6)

prompt总是返回一个字符串。

如果您想在计算中使用该输入,则必须使用parseIntparseFloat

var answer1 = parseInt(prompt("Question 1"));
var answer2 = parseFloat(prompt("Question 2"));

也就是说,除法和乘法运算符会将它的参数强制转换为数字。

当这种强制行为不起作用时会出现问题:price2 = (0.1+price1);
在那里,因为+只会将2个参数连接为字符串,如果price2"0.11.54"price1可以是"1.54"之类的字符串。
尝试将任意数字乘以无效数字会产生NaN

将用户输入从字符串转换为数字可以解决该问题,因为+可以将这两个数字加在一起,而不是将它们连接起来。