It wont compile!

I know something is probably wrong with my if condition but im unsure of what.

if (weight > 200)            
                shipping_cost = 49.95;
           else if (weight >= 100 & < 200)
                shipping_cost = 39.95;
           else if (weight >= 50 & < 100)
                shipping_cost = 24.95;
           else if (weight >= 20 & < 50)
                shipping_cost = 15.95;
           else 
                shipping_cost = 11.95;

Thanks

Recommended Answers

All 3 Replies

It wont compile!

I know something is probably wrong with my if condition but im unsure of what.

if (weight > 200)            
                shipping_cost = 49.95;
           else if (weight >= 100 & < 200)
                shipping_cost = 39.95;
           else if (weight >= 50 & < 100)
                shipping_cost = 24.95;
           else if (weight >= 20 & < 50)
                shipping_cost = 15.95;
           else 
                shipping_cost = 11.95;

Thanks

1. Your using bitwise instead of logical ANDs. Change them to &&

2. You can't use standard algebraic notataion. You need to do 2 separate evaluations.
i.e. else if (weight >= 100 && weight < 200)

>else if (weight >= 100 & < 200)
"else if weight is greater than or equal to 100 and less than 200". That makes perfect sense, but it's wrong. C++ won't infer that in the second half of the expression you're still trying to compare with weight. Further, & is the bitwise AND operator, not the logical AND:

else if (weight >= 100 && weight < 200)

Apply that to the other clauses and see how you fare.

commented: Thanks +1

Thanks, I figured it out. This works.

if (weight > 200)            
        shipping_cost = 49.95;
     else if (weight >= 100 && weight < 200)
        shipping_cost = 39.95;
     else if (weight >= 50 && weight < 100)
        shipping_cost = 24.95;
    else if (weight >= 20 && weight < 50)
       shipping_cost = 15.95;
     else 
         shipping_cost = 11.95;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.