【问题标题】:javascript numbers assignmentjavascript 数字赋值
【发布时间】:2023-02-20 05:23:40
【问题描述】:

我的脚本的最后两个 console.logs 有一些问题。我应该为两者输出数字,但我得到的是 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() 但我没有得到我正在寻找的结果。

【问题讨论】:

  • 提示:Template literals 存在,可以帮助清理这段代码。
  • 提示:如果你有数字,你可以在不解析的情况下对它们进行数学运算。他们是已经数字。放下parseFloat,走开!
  • @tadman,我的教授希望我们在这个非常漫长的开始过程中做到这一点。我不允许使用他没有教给我们的任何东西。

标签: javascript


【解决方案1】:

错误 1. 复制/粘贴

这行代码是错误的:

let secondTotal = parseFloat(firstCost * firstAmount);

您已复制并粘贴,但没有将“第一”更改为“第二”。

错误2.你还没有决定tax是百分比还是小数

您正在收集一个整数,即 5% 的税将存储为 5。

但是你把它当作一个分数来使用(例如 5% 表示为 0.05),只需将它乘以小计即可。

错误 3. 输入数据时您使用“取消”来跳过税值

这导致它将 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2019-10-21
    • 2011-01-20
    • 2017-10-12
    • 2013-01-22
    • 2010-12-17
    相关资源
    最近更新 更多