我一直收到 NaN,但我找不到解决方法

I keep getting NaN and i can't find out how to fix it

它发生在到达 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>

prompt总是returns一个字符串。

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

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

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

当此强制转换不起作用时出现问题:price2 = (0.1+price1);
在那里,因为 + 只是将 2 个参数连接为字符串,如果 price1"1.54".[=32=,price2 可以是类似 "0.11.54" 的字符串] 尝试将任何数字与无效数字相乘会导致 NaN.

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