You are here:

C++/if and else if problem

Advertisement


Question
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>


using namespace std;

int main()
{
 char fare;
 char s,c,g;
 int num1, num2, num3, num4;
 double depart = num1 + (num2/60);
 double arrive = num3 + (num4/60);
 double duration = (num3&&num4) - (num1&&num2);
 double cost;

 cout << "This program will calculate a single, couple, or group "
      << "\nfare amount which is then owed by the customer for the trip.\n"
      << "\nTo calculate a single fare amount, input S (or s)"
      << "\nTo calculate a couple fare amount, input C (or c)"
      << "\nTo calculate a group fare amount, input G (or g)"
      << " \n\nInput S, C, or G: ";
 cin >> fare;
      
 if(fare=='S'||fare=='s')
 {
  cout <<"\nWhat hour did they depart? ";
  cin>>num1;
  cout<<"\nWhat minute did they depart? ";
  cin >> num2;
  cout << "\nYou entered for departure: " << num1 << ":" << num2 << endl;
  cout <<"\nWhat hour did they arrive? ";
  cin>>num3;
  cout<<"\nWhat minute did they arrive? ";
  cin>>num4;
  cout << "\nYou entered for arrival: " << num3 << ":" << num4 << "\n" << endl;
  cout << "A rickshaw departed at " << num1 << ":" << num2
       << " and arrived at " << num3 << ":" << num4 << " with a single customer.\n" << endl;
       
 if(duration <= 30.0)   
 {
  cout << "You owe $7.00.\n" << endl;
  }
else if (duration > 30.0)
{
cost =(duration - 30.0) * (1.50);
cout << "You owe " << cost << "." << endl;
     }
}
    system("pause");
    return 0;
}
    
  
* I can make the program run that is you enter a number <=30 then you will owe $7.00 but I can't make it go to the next else if, if I enter a number greater than 30.

I need help.

Answer
Well as far as I can tell the main problem is that you have assumed that the lines:

 double depart = num1 + (num2/60);
 double arrive = num3 + (num4/60);
 double duration = (num3&&num4) - (num1&&num2);

Define calculations that should be performed to produce the values of depart, arrive, and duration from num1, num2, num3, num4 when ever num1, num2, num3 or num4 are changed. They do not. They evaluate what is on the right hand side of the = , come up with a value, convert the value to the required type if necessary (and possible) and store it in the variable on the left hand side of the =. That's it. All done.

If later you change the value of one of the variables used in the right hand side expressions it does NOT mean that any and all previous expressions mentioning it are reevaluated and any variables that would be changed as a result modified to suit.

Hence saying:

 int num1, num2, num3, num4;
 double depart = num1 + (num2/60);

Sets num1, num2, num3, num4 to random rubbish (i.e. they are uninitialised, which is the default for automatic function local variables), then uses these undetermined values to calculate:

   num1 + (num2/60)

The value that is the result of evaluating this expression is an int type value so is converted to a double and used to initialise the value of the depart variable. Note that because num1 and num2 are uninitialised and therefore have undetermined values the value of depart will also be undetermined.

If you then went on to set num1 and num2 to some known values:

   num1 = 10;
   num2 = 20;

The value of depart IS NOT CHANGED - there is no connection between depart and the expression you used to set its initial value, nor any other variables you use in such expressions.

The variables arrive and duration work in a similar manner.

Hence as you only ever set the values of depart, arrive and duration once using expressions that use the values of variables that are uninitialised and therefore have undetermined values, and inputting values for num1, num2, num3 and num4 has NO EFFECT WHATSOEVER on the value of duration which presumably happens to have ended up with a value from the initial expression evaluation of

   (num3&&num4) - (num1&&num2);

that is less than 30 your else if clause is never taken.

This low value of duration is in fact very likely as && is the C ands C++ operator for the Boolean AND operation and the initial expression used to set its value is equivalent to:

   (num3!=0 AND num4!=0) - (num1!=0 AND num2!=0)

Where != is the C and C++ operator for not equals. Note that this is a C and C++ convention - any value that is not zero is considered to be true in Boolean expressions.

Each part in parentheses will evaluate to true or false which will be converted to the integer value of 1 for true or 0 for false. Hence the possible values for duration will be:

   0 - 0 = 0
   0 - 1 = -1
   1 - 0 = 1
   1 - 1 = 0

In fact they will be 0.0, -1.0, 1.0 and 0.0 as the integer result of the expression needs to be converted to a double value.

So what you need to do is move your calculations for depart, arrive and duration to a point in the program logic where you have values for num1, num2, num3 and num4. In C++ you can define variables anywhere in a function (or compound block) not just at the top. Hence the easiest initial fix would be to move the definitions of depart, arrive and duration to a point after you have read the values from the user, in fact you can also move the definitions of num1, .. num4 into the if { ... } block as well as they are not used until this point:


       ...

     if(fare=='S'||fare=='s')
     {

         int num1, num2, num3, num4;

         ...

         cout << "A rickshaw departed at " << num1 << ":" << num2
         << " and arrived at " << num3 << ":" << num4 << " with a single customer.\n" << endl;

        // You now have values for num1, num4. Define duration and initialise it with
        // a values based on these values:
        
         double duration = (num3&&num4) - (num1&&num2);

         ...

You will of course still have to fix the initialisation expression for duration - I have no idea what you thought the && operator was useful for in this situation sorry.

Also I am not sure what the  variables

 char s,c,g;

are for as you never seem to use them after they are defined.

Also:

 double depart = num1 + (num2/60);
 double arrive = num3 + (num4/60);

Are not used elsewhere after they are defined. I guess in this case they should be used to help calculate duration and so should be defined just before duration and the initialisation expression for duration should be the difference between the arrival time and the departure time.

Finally note that if num2 and num4 are integer value in the range 0 to 59 (for minutes) the:

   num2 / 60

and:

   num4 / 60

will give a result of 0 for values less than 60 as _both_ num2 (or num4) and 60 are integer and integer division _truncates_ any fractional parts (i.e. the remainder is lost). Hint: try using 60.0 instead as 60.0 represents a double literal value - this will make the division floating point and num2 and num4 will be converted to double as will num1 and num3.

Hope this helps

Additional
----------
Oh after I posted you my answer it occurred to me that your arrival and departure calculations seem to calculate _hours_ hence would duration (when properly calculated) also be in hours?

If so then is that value of 30.0 that you are testing for supposed to be for 30.0 hours or did your mean 30 minutes (i.e. 0.5 hours)?

Oh and if something is not <= some value it must be > than some value.

Hence could you not just write:

   if ( duration <= 30.0 )
   {
   ...
   }
   else // duration *must be* > 30.0 so no need for another if
   {
   ...
   }

On the other hand if you needed different fares for say <= 30.0, > 30.0 and <= 60.0, > 50.0 and <= 120, and everything else then you would need some if .. else if .. constructs:

   if ( duration <= 30.0 )
   {
   ...
   }
   else if ( duration <= 60.0 )
   {
   ...
   }
   else if ( duration <= 120.0 )
   {
   ...
   }
   else // duration more than 120.0
   {
   ...
   }  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.