javascript编号分配



我对最后两个控制台有一些问题。我的脚本日志。我应该有数字输出,但我得到NAN

alert("Let's make a shopping list!");
let first = prompt("What is the first item?");
let firstCost = Number(prompt("What is the cost of " + first + "?"));
let firstAmount = Number(prompt("How many of " + first + " would you like?"));
let second = prompt("What is the second item?");
let secondCost = Number(prompt("What is the cost of " + second + "?"));
let secondAmount = Number(prompt("How many of " + second + " would you like?"));
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);
let secondTotal = parseFloat(firstCost * firstAmount);
let subTotal = parseFloat(firstTotal + secondTotal);
let taxTotal = parseFloat(subTotal * tax);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log(first + " " + firstCost + " " + firstAmount + " " + 
firstTotal);
console.log(second + " " + secondCost + " " + secondAmount + " " + 
secondTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);

我将所有的Number()更改为parseFloat(),但我没有得到我想要的结果。

错误1。复制/粘贴

这行代码是错误的:

let secondTotal = parseFloat(firstCost * firstAmount);

你已经复制粘贴了,没有更改"first";second" .

错误2。您还没有决定tax是百分比还是小数

您正在收取一个INTEGER,即5%的税将存储为5。

但你使用它就好像它是一个分数(例如5%表示为0.05),只需乘以小计。

错误3。输入数据时,您使用'cancel'来跳过税值

这会导致它将NaN存储在税中,并且会打乱所有依赖于税的输出。

提示。为了快速得到答案,去掉所有不相关的代码,并使其在Stack Overflow中可运行,使用"<>"图标。

这有助于别人帮助你。

let firstCost = Number(prompt("What is the cost of first ?"));
let firstAmount = Number(prompt("How many of first would you like?"));
let secondCost = Number(prompt("What is the cost of second?"));
let secondAmount = Number(prompt("How many of second would you like?"));
// In this next line you are storing an integer (e.g. 5, for 5 percent) 
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);

// This next line is a mistake
// let secondTotal = parseFloat(firstCost * firstAmount); 
// You meant this:
let secondTotal = parseFloat(secondCost * secondAmount);

let subTotal = parseFloat(firstTotal + secondTotal);
// But in this line you are treating it as though it is a decimal, e.g. 0.05 for 5 percent.
// let taxTotal = parseFloat(subTotal * tax);
// You probably meant this:
let taxTotal = parseFloat(subTotal * tax/100);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);

最新更新