T Figmiester
T Figmiester

Reputation: 43

Need assistance with this if statement

first, let let me show you the code:

// calculate grand total
if(unitsPurchased >= 10,19)
{
    discount = .20;
    totalCost = totalCost - (totalCost * discount);
    cout << fixed << setprecision(2);
    cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total is: $" << totalCost << endl;
}

I'm trying to apply a 20% discount if a person buys between 10 to 19 items. how can I alter my if statement to reflect this? I've tried using AND (&&) but that didn't work. how can I set the range between two numbers?

Upvotes: 1

Views: 76

Answers (5)

Desmond9989
Desmond9989

Reputation: 25

if(unitsPurchased > 10 && unitsPurchased < 19){
     
}

Do it this way.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881453

The statement you're looking for is one of:

if (unitsPurchased >  10 && unitsPurchased <  19) { // exclude 10, 19
if (unitsPurchased >= 10 && unitsPurchased <  19) { // include 10, exclude 19
if (unitsPurchased >= 10 && unitsPurchased <= 19) { // include 10, 19

An expression like valA, valB is actually a use of the comma operator which will evaluate both valA and valB but result in the single value valB.

In your particular case, it's more complicated since the comma operator has a relatively low precedence, so unitsPurchased >= 10, 19 means (unitsPurchased >= 10), 19, which equates to:

  • evaluate unitsPurchased >= 10;
  • evaluate 19;
  • use the value 19.

Since 19 is non-zero, it is considered true. Hence your business is more likely to go bankrupt since every single purchase results in a 20% discount :-)

Upvotes: 4

atakanyenel
atakanyenel

Reputation: 1375

The other answers are correct and I want to give a heads-up if anyone comes across this.

Don’t write 10 <= unitsPurchased <= 19. That will be a buggy statement in many languages(not all). If unitsPurchased is 20 , the first part of the statement will be correct and even though the second part is wrong, it will return true.

This was a mistake I made in my first ever programming exam.

Upvotes: 0

Paul Evans
Paul Evans

Reputation: 27577

You'll have to use the && (and) operator:

if(unitsPurchased >= 10 && unitsPurchased <= 19)
{
    discount = .20;
    totalCost = totalCost - (totalCost * discount);
    cout << fixed << setprecision(2);
    cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total is: $" << totalCost << endl;
}

Upvotes: 0

Christopher Miller
Christopher Miller

Reputation: 3461

You can do it like this:

if(unitsPurchased > 10 && unitsPurchased < 19){
    discount = 0.2; 
}

This if-statement checks if unitsPurchased is greater than 10 and if it is less than 19, which is exactly what you want.

Upvotes: 0

Related Questions