No errors, logic error? please help

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."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
using namespace std;

int main()
{
 double w;
 
 cout << "enter the weight" << endl;
 cin >> w;
 
 if ( 0 < w <= 1 )
   cout << "cost is 3.50" << endl;
   else if ( 1 < w <= 3) 
     cout << "cost is 5.50" << endl;
     else if (3 < w <= 10)
       cout << "cost is 8.50" << endl;
       else if (10 < w <= 20)
         cout << "cost is 10.50" << endl;
         else if (20 < w <=50)
         cout << "cost is 13.50" << endl;
           else if ( w > 50)
           cout << "the package cannot be shipped." << endl;
 
 
  return 0;
}
 
Results from running:
Run Status from Test Data Set 2: 15ms CPU time used
enter the weight
3
cost is 3.5

Incorrect!
Hint: The input for this test is
3

The expected output pattern is 5.5.
if ( 0 < w <= 1 )

This doesn't do what you think.

You probably wanted to do this:

if( 0 < w && w <= 1 )


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;
else if ( 1 < w <= 3) 
    cout << "cost is 5.50" << endl;


// Better
if( w <= 0 )
    cout << "Invalid input" << endl;
else if( w <= 1 )                       // the 'else' ensures w>0, no need to check that again
    cout << "cost is 3.50" << endl;
else if( w <= 3 )                       // the 'else' ensures w>1, no need to check that again
    cout << "cost is 5.50" << endl;
Okay I see, I got it correct now, though the line
if( 0 < w && w <= 1 ) would not work.

So I realize I don't need the redundant else if ( 1 < w <= 3). thanks,

So I then seperated the first if like you did.
instead of if ( 0 < w <= 1 )
I did if( w <= 0 )
cout..
else if( w <= 1 )
cout..

I understand this now thanks again, however the && didnt work i tried that first
however the && didnt work i tried that first


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.
Yeah your right I forgot to do the && to every one of them, makes sense
Topic archived. No new replies allowed.