我的任务是:
每件商品售价99美元。
你得到的折扣不低于10,所以1-9。
您可以以10-19的价格获得5%的折扣。
您可以获得20%的折扣10%。
当我在文本框中添加1-9个数字时,它不会应用优惠的折扣。当我把10-19,它适用5折优惠。但是当我把20或更高的数字放入时,它仍然适用5%的折扣而不是10%的折扣。
我的代码:
$bits()
答案 0 :(得分:3)
这样做。在您的第一个上添加额外的条件运算符,如果在两个数字条件之间作出反应。
if (dblQuantitySold >= 10 && dblQuantitySold < 20)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.05;
MessageBox.Show("A 5% discount will be given because 10 or more has been sold.");
}
答案 1 :(得分:2)
这是因为您的if
语句的顺序错误。首先检查项目是否大于或等于10,其中包括所有大于20的值。只需先检查>=20
:
if (dblQuantitySold >= 20)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.10;
MessageBox.Show("A 10% discount will be given because 20 or more has been sold.");
}
else if (dblQuantitySold >= 10)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.05;
MessageBox.Show("A 5% discount will be given because 10 or more has been sold.");
}
答案 2 :(得分:1)
试试这个:
if (dblQuantitySold >= 20)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.10;
MessageBox.Show("A 10% discount will be given because 20 or more has been sold.");
}
else if (dblQuantitySold >= 10)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.05;
MessageBox.Show("A 5% discount will be given because 10 or more has been sold.");
}
您的条件顺序错误。
如果您想获得奖励积分,请尝试以下代码:
decimal price = 99;
decimal quantitySold = decimal.Parse(txtQuantity.Text);
var discounts = new[]
{
new { percentage = 0.0m, threshold = 0 },
new { percentage = 0.05m, threshold = 10 },
new { percentage = 0.1m, threshold = 20 },
};
var discount =
discounts
.OrderBy(d => d.threshold)
.Where(d => d.threshold <= quantitySold)
.Last();
decimal amountTotalDue = quantitySold * price * (1m - discount.percentage);
if (discount.percentage > 0m)
{
var message = String.Format(
"A {0:0%}% discount will be given because {1} or more has been sold.",
discount.percentage,
discount.threshold)
MessageBox.Show(message);
}
lblAmountDueTotal.Text = amountTotalDue.ToString("C");
这里的优点是您可以将折扣结构与计算折扣的代码分开。这使您可以将折扣提取到文件或数据库中,并允许应用程序轻松自定义。