Eric Eric -4 years ago 75
C# Question

Hey, guys! I'm working on an assignment with C#. I'm using if-else

My assignment is:


Each item sold is $99.

You get no discount selling under 10, so 1-9.

You get a 5% discount selling 10-19.

You get a 10% discount selling 20+.


When I put 1-9 numbers in my textbox, it doesn't apply the discount which is good. When I put 10-19, it applies the 5% off discount. But when I put 20 or any numbers higher, it still applies the 5% off discount and not a 10% discount.

My code:

double dblQuantitySold;
double dblAmountTotalDue;
double dblPrice = 99;

//Acquire the math.
dblQuantitySold = double.Parse(txtQuantity.Text);
dblAmountTotalDue = dblQuantitySold * dblPrice;

//Create the solution for your if-else statement.
if (dblQuantitySold >= 10)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.05;
MessageBox.Show("A 5% discount will be given because 10 or more has been sold.");
}
else if (dblQuantitySold >= 20)
{
dblAmountTotalDue -= dblQuantitySold * dblPrice * 0.10;
MessageBox.Show("A 10% discount will be given because 20 or more has been sold.");
}

//Display the results.
lblAmountDueTotal.Text = dblAmountTotalDue.ToString("C");

Answer Source

It's because you have the if statements in the wrong order. You first check if the item is greater than or equal to 10, which includes all values greater than 20. Just put the check for >=20 first:

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.");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download