【问题标题】:Set variable to itself plus another variable in JavaScript将变量设置为自身加上 ​​JavaScript 中的另一个变量
【发布时间】:2019-01-05 16:58:00
【问题描述】:

我在我的 CS 课上制作了一个更复杂(尽管只是稍微复杂一点)的程序,它根据一些规则运行了一些计算和折扣。它是用 Java 编写的,可以读取并输出到文件中。我正在尝试在 JavaScript 中重做它,循环输入输入并在之后应用计算。我会在第二个 while 循环关闭后调用这两个函数。

我的问题是 priceCount 完全按价格递增,而 qty 似乎只是吐出一些随机数(但是它们都是输入的倍数),前导 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");

【问题讨论】:

  • prompt 的输入是字符串。在执行qty = qty + amount 之类的操作之前,您需要先将它们转换为数字
  • 我实际上没有看到你调用过discountCalcadjust 函数。您打算在哪里/如何包含它们?
  • 关于你的 if 条件的小事:你不需要每次都检查下边界。如果程序的控制流到达discountCalc函数中的第二个条件,amount肯定大于30,以此类推。
  • discountCalc 将在每个价格金额对的末尾调用,在第二个 while 循环之后生成新发票之前调用调整。我明白你所说的关于下界的说法。谢谢。

标签: javascript variables variable-assignment increment


【解决方案1】:

Prompt 返回一个字符串,因此您应该将其转换为数字。 您可以使用 parseInt()、parseFloat() 或 Number()。 parseInt() 返回一个整数值,而 parseFloat() 返回一个浮点数。 Number() 可以同时返回两者,但如果提示返回的字符串不计算为数字,则返回 NaN。检查用户是否提供了无效数据会很有用。

所以替换

qty = qty + amount

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

如果您有其他区域添加金额,您可以这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2010-11-04
    • 2023-03-24
    • 2017-01-18
    • 1970-01-01
    相关资源
    最近更新 更多