如何检查价格是否超过600

时间:2015-10-10 17:58:07

标签: javascript

课程教程 - 如果声明

向当地超市和大型便利店出售面包的小面包店的运作基础如下:

  • 少于50个面包的订单价格为每个面包1.10欧元
  • 50至90个面包的订单价格为每片0.95欧元
  • 90个面包以上的订单价格为每块0.85欧元。

提示用户输入他们想要购买的面包数量。 在文本框中显示订单的总价

如果订单总金额超过€60,则会在文本框中显示一条消息,告知用户任何额外的煎饼订单都可以享受20%的折扣。

我的问题是 这是这个问题的答案,因为我是javascript的新手? 如果没有人可以给我一个正确的答案吗?

我正在努力在文本框中显示答案,而且我正在努力显示消息说你可以享受20%的折扣,因为我不知道如何检查价格是否超过600还有一件事 你可以检查一下我用过的变量吗?

var n = prompt("Check your number", "How many items you want to buy?");

n = parseInt(n);

if (n  < 50)
   {
   alert("Total items you want to buy is  = " + n + "   The total price for these items is   =  " + n*1.10 + "  Euro");
   }
else if (n > 50 && n < 90)
   {
   alert("Total items you want to buy is  = " + n + "   The total price for these items is   =  " + n*0.95 + "  Euro");
   }

else if (n > 200)
   {
   alert("Total items you want to buy is  = " + n + "   The total price for these items is   =  " + n*0.85 + "  Euro");
   }
   else {
   alert("Please enter a valid number");
}

1 个答案:

答案 0 :(得分:1)

简答:不,你的剧本不正确。

答案很长:

您不检查n是否为正整数。如果错误parseInt()返回NaN,您可以使用isNaN()进行检查。您也可以删除前导零,一些较旧的引擎(&lt; ECMA-Script 5)可能会将这些数字视为八进制,无论哪个基数被赋予parseInt()的第二个参数。

n = parseInt(n);
if(isNaN(n) || n <= 0){
  alert("We, as the respectable bakery we are, "
         +"must insist on positive whole numbers. "
         +"Thank you for your patience");
}
else{
  // go on with the business
}

您不提供准确销售50个面包的数量,价格范围也包括90个面包。将相应的行更改为

if(n >=50 && n<= 90){
  // set proper price
}

20%-off是煎饼而不是面包,你需要在一个变量中保留总和,让我们称之为totalSum,并在所有混乱检查结束时

if(totalSum >= 60){
  aler("You are entitled to a 20% discount for you next purchase of "
  +"pancakes! Buy some now, they are really yummy!");
}

计算机也可以使重复性任务变得更简单。你有三个相同的两个句子的项目数和总和的单一差异。把它们放在变量中。

var totalItemString = "Total items you want to buy is = ";
var totalSumString = " The total price for these items in Euro is = ";

注意:在浮动计算中计算是危险的。货币。在你的情况下,用美分而不是欧元来做所有事情,并且仅为打印输出除以100。您可以使用toFixed()

但是,金融计算很复杂,甚至部分甚至受法律管制(当然,取决于管辖权)。不应该打扰你作为一个初学者,但如果你喜欢编程并想继续它:不要忘记它。