将变量设置为自身加上 ​​JavaScript 中的另一个变量

Set variable to itself plus another variable in JavaScript

我在我的 CS class 中做了一个更复杂的(虽然只是一点点)程序,运行 根据一些规则进行一些计算和折扣。它是用 Java 编写的,读取并输出到文件。我正在尝试在 JavaScript 中重做它,循环接受输入并在之后应用计算。我会在第二个 while 循环结束后调用这两个函数。

我的问题是 priceCount 完全按价格递增,而 qty 似乎只是吐出一些 运行dom 数字(然而,它们都是输入的倍数),前导 0。这里发生了什么?它与 priceCount 的逻辑完全相同,但根本不起作用。我尝试移动变量,认为这是一个范围问题,但没有任何效果。

我希望我问的不是一个已经回答了很多次的问题。我尝试广泛搜索,但这本身就是一种技能,我很难将我的问题表述为关键词。任何和所有输入将不胜感激。

    function discountCalc (price, amount) {

  var discount;

  if (amount <= 30){
    discount = oldPrice * 0.05;
  }
  else if (amount >= 30 && amount <= 50){
    discount = oldPrice * 0.1;
  }
  else if (amount >= 51 && amount <= 75){
    discount = oldPrice * 0.25;
  }
  else {
  discount = oldPrice * 0.4;
  }
return discount;
}

function adjust(newPrice, amount){

  var adjust;

  if (newPrice < 500){
    adjust = -20;
  }
  else if (newPrice >= 500 && amount < 50){
    adjust = newPrice * 0.05;
  }
  else{
    adjust = 0;
  }
  return adjust;
}

var answer = "new", price, amount, customer = 1;

while (answer !== "quit" && answer !== "Quit" && answer !== "q" && answer !== "Q") {

console.log("invoice # 000" + customer);

if (answer == "new" || answer == "New") {

customer = customer + 1;

    var another = "yes";

var priceCount = 0;
var qty = 0;

    while (another == "yes" || another == "Yes" || another == "y" || another == "Y"){

  price = prompt("price?");
  amount = prompt("amount?");
  qty = qty + amount;
  priceCount = priceCount + (price * amount);
  console.log("Price: " + price + " Amount: " + amount);
  another = prompt("type yes for another, any key to stop");

}

console.log("Total price is: " + priceCount);
console.log("Total items: " + qty);

priceCount = 0;
qty = 0;

}

answer = prompt("new or quit?");
}

console.log("thanks");

提示return是一个字符串,所以你应该把它转换成一个数字。 您可以使用 parseInt()、parseFloat() 或 Number()。 parseInt() return 是一个整数值,parseFloat() return 是一个浮点数。 Number() 可以 return 两者,但如果提示 returns 字符串的计算结果不是数字,它 returns NaN。检查用户是否提供了无效数据可能很有用。

所以替换

qty = qty + amount

qty = qty + Number(amount) //or parseInt(amount), parseFloat(amount)

如果你有其他地区给一个数字加amount,你也可以这样做。