I have this program homework,
I get no error when it runs but wrong answer.
A shipping company uses the following function to calculate the cost(in dollars) of shipping based on the weight of the package (in pounds).
c(w)=
3.5, if 0 < w <= 1
5.5, if 1 < w <= 3
8.5, if 3 < w <= 10
10.5, if 10 < w <= 20
Write a program that prompts user to enter the weight of the package and display the shipping cost. If the weight is greater than 50, display a message "the package cannot be shipped."
Also note that the 'else' guarantees the previous if statement was false, so including lower bounds in these is redundant. Redundant code is bad:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Bad - redundant
if ( 0 < w <= 1 )
cout << "cost is 3.50" << endl;
elseif ( 1 < w <= 3)
cout << "cost is 5.50" << endl;
// Better
if( w <= 0 )
cout << "Invalid input" << endl;
elseif( w <= 1 ) // the 'else' ensures w>0, no need to check that again
cout << "cost is 3.50" << endl;
elseif( w <= 3 ) // the 'else' ensures w>1, no need to check that again
cout << "cost is 5.50" << endl;
It should have. You must have done it wrong. Keep in mind you'd have to do that for all your if statements because you're making that mistake several times.
But really... the else/if solution without any &&s is superior, so whatever.