到达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始终返回一个字符串。

如果要在计算中使用该输入,则必须使用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

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

09-25 18:48