Like Tree1Likes

if statement problem.....

This is a discussion on if statement problem..... within the C++ Programming forums, part of the General Programming Boards category; Hi all, I'm doing some practise exercises from a textbook but I've hit a snag and I can't see where ...

  1. #1
    Registered User JM1082's Avatar
    Join Date
    Mar 2011
    Posts
    51

    Wink if statement problem.....

    Hi all,

    I'm doing some practise exercises from a textbook but I've hit a snag and I can't see where I might be going wrong!

    When using the nextDay() function, I'm expecting the date1 object to go into the next year. However, it doesn't reset the month value to 1 or increment the year value.

    If you see where the error lies please leave a corrective suggestion.

    Please see my code below:

    Code:
    // Fig. 9.19: fig09_19.cpp
    // Demonstrating that class objects can be assigned
    // to each other using default memberwise assignment
    #include <iostream>
    #include "Date.h" // include definition of class Date from Date.h
    using namespace std;
    
    int main()
    {
        Date date1( 31, 12, 2004 );
    
        cout << "date1 = ";
        date1.print();
    
        date1.nextDay();
    
        cout << "\ndate1 = ";
        date1.print();
    } // end main
    Code:
    // Fig. 9.17: Date.h
    // Date class declaration.  Member function are defined in Date.cpp.
    
    // prevent multiple inclusions of header file
    #ifndef DATE_H
    #define DATE_H
    
    // class Date definition
    class Date
    {
    public:
        Date( int = 1, int = 1, int = 2000 ); // default constructor
        void print();
        void nextDay();
        int monthsDays( int );
    private:
        int month;
        int day;
        int year;
    }; // end class Date
    
    #endif // DATE_H
    Code:
    // Fig. 9.18: Date.cpp
    // Date class member-function definitions.
    #include <iostream>
    #include "Date.h" // include definition of class Date from Date.h
    using namespace std;
    
    // Date constructor (should do range checking)
    Date::Date( int m, int d, int y )
    {
        month = ( m > 0 && m < 13 ) ? m : 1;
        day = ( d > 0 && d < ( monthsDays( m ) ) ) ? d : 1;
        year = ( y > 1999 && y < 2199 ) ? y : 2000;
    } // end constructor Date
    
    // return the number of days for each month
    int Date::monthsDays( int m )
    {
        switch ( m )
        {
            case 1: return 32;
                break;
            case 2: return 29;
                break;
            case 3: return 32;
                break;
            case 4: return 31;
                break;
            case 5: return 32;
                break;
            case 6: return 31;
                break;
            case 7: return 32;
                break;
            case 8: return 32;
                break;
            case 9: return 31;
                break;
            case 10: return 32;
                break;
            case 11: return 31;
                break;
            case 12: return 32;
                break;
    
        } // end switch
    } // end function monthsDays
    
    // print Date in the format mm/dd/yyyy
    void Date::print()
    {
        cout << month << '/' << day << '/' << year;
    } // end function print
    
    // increment the day by 1
    void Date::nextDay()
    {
        day++;
        switch ( month )
        {
            case 1: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 2: if ( day == 31 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 3: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 4: if ( day == 31 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 5: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 6: if ( day == 31 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 7: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 8: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 9: if ( day == 31 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 10: if ( day == 32 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 11: if ( day == 31 )
                    {
                        day = 1;
                        month++;
                    } // end if
                break;
            case 12: if ( day == 32 )
                    {
                        day = 1;
                        month = 1;
                        year++;
                    } // end if
                break;
        } // end switch
    } // end function nextDay

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,830
    > Date date1( 31, 12, 2004 );
    This looks like DMY

    > Date::Date( int m, int d, int y )
    This expects MDY

    If you added some final 'else' clauses or 'default' to your switch/case to complain loudly when you get to the unusual cases, you would have seen that.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User JM1082's Avatar
    Join Date
    Mar 2011
    Posts
    51
    Who's a silly boy then? ;-)

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,625
    I noticed that in "monthsDays()", you return 29 for February! That is true only when "year" is a multiple of 4 and not of 100, or when it's a multiple of 400. Otherwise you should return 28.

    EDIT: Also, your "nextDay()" won't work as you wish when February.

    EDIT^2: O_o, why does your "monthsDays()" return one greater for all months?!
    Last edited by GReaper; 09-07-2011 at 04:48 PM.
    Devoted my life to programming...

  5. #5
    Registered User
    Join Date
    Aug 2011
    Location
    Montreal, Quebec, Canada
    Posts
    73
    Because he uses < instead of <=.

  6. #6
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,528
    Another suggestion, since your two switch-cases are somewhat similar, you could use a std::map to make the code much more 'elegant' .
    Put a global map like this:
    Code:
    std::map<int,int> month_day=
    {
        {1,32},
        {2,29},
        {3,32},
        //and so on
    }
    Remember that you have to have the c++0x flag enabled for the initializer list to work. Else just put an init function and insert the values with the insert member function or just by assigning to the indices .

    For using it, instead of your function call just use
    eg:
    Code:
    month_day[2] for getting a value of 29 .
    Last edited by manasij7479; 09-07-2011 at 08:07 PM.
    Manasij Mukherjee | gcc-4.9.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  7. #7
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    Elegant you say? 30 days hath September April, June, and November, excepting February when comes the time every leap year gives it twenty-nine. A fine switch case that will make.

  8. #8
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,528
    Quote Originally Posted by whiteflags View Post
    Elegant you say? 30 days hath September April, June, and November, excepting February when comes the time every leap year gives it twenty-nine. A fine switch case that will make.
    Agreed.
    I forgot one could omit break;s
    Manasij Mukherjee | gcc-4.9.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Interested in the easy way?

    Code:
    // is this leap year  1 = yes, 0 = no
    int IsLeapYear(int Year)
      { return !(Year % 4); }
    
    
    // how many days this month
    int DaysPerMonth(int Month, int Year)
      { int days[] = {0,31,28,31,30,31,30,31,31,30,31,31,31};
         if (IsLeapYear(Year))
           days[2]++;
         return days[Month]; }
    
    
    // get tomorrow's date
    void GetTomorrow(int *Day, int *Month, int *Year)
      { (*Day)++;
         if (*Day > DaysPerMonth(*Month, *Year))
           { *Day = 1;
              (*Month)++; }  
         if (*Month > 12)
           { *Month = 1;
              (*Year)++; } }
    
    
    // what day of the year is it?
    int GetDayOfYear(int Day, int Month, int Year)
      { int i;
         int yday = 0;
         for (i = 1; i < Month; i++)
            yday += DaysPerMonth(i,Year);
         return yday + Day; }
    Sometimes it really pays to think in smaller blobs...

    EDIT: Tossed in a couple more.
    Last edited by CommonTater; 09-07-2011 at 10:32 PM.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    int IsLeapYear(int Year)
      { return !(Year % 4); }
    I think there are exceptions to this. Something like if it's divisible by 2000? or 200? Here we go: Leap year - Wikipedia, the free encyclopedia


    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by quzah View Post
    Code:
    int IsLeapYear(int Year)
      { return !(Year % 4); }
    I think there are exceptions to this. Something like if it's divisible by 2000? or 200? Here we go: Leap year - Wikipedia, the free encyclopedia


    Quzah.
    Ummmm.... Yoiks! Do you think they could have possibly made that any more complex?

    The good news is that we don't appear to be in trouble until 2100... I can live with that

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    6,643
    Quote Originally Posted by CommonTater View Post
    Ummmm.... Yoiks! Do you think they could have possibly made that any more complex?
    Well, to be fair, the reason for a leap-year (a day containing an extra year) is to synchronise the calendar year with astronomical year (the time it takes for the earth to circumnavigate the sun) or seasons. Since the astronomical year is a bit more than 365 days, and people would not take kindly to years with partial days, the only correction schemes possible involve adding whole days here and there.

    The alternative would have been to slow down the speed at which the earth circumnavigates the sun so it was exactly 365 days. If you think the scheme of leap-years is complex, bear in mind it was much simpler than devising a machine that could slow down the earth without killing everyone on the planet.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by grumpy View Post
    Well, to be fair, the reason for a leap-year (a day containing an extra year) is to synchronise the calendar year with astronomical year (the time it takes for the earth to circumnavigate the sun) or seasons. Since the astronomical year is a bit more than 365 days, and people would not take kindly to years with partial days, the only correction schemes possible involve adding whole days here and there.

    The alternative would have been to slow down the speed at which the earth circumnavigates the sun so it was exactly 365 days. If you think the scheme of leap-years is complex, bear in mind it was much simpler than devising a machine that could slow down the earth without killing everyone on the planet.
    LOL... Ya think???

    Warning... totally untested...
    Code:
    // is this leap year  1 = yes, 0 = no
    int IsLeapYear(int Year)
      { if (! (Year % 100))
          Year /= 100;
        return !(Year % 4); }
    Last edited by CommonTater; 09-08-2011 at 08:37 AM.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,013
    Quote Originally Posted by CommonTater View Post
    ...

    Sometimes it really pays to think in smaller blobs...

    EDIT: Tossed in a couple more.
    It also helps to use references where proper and not pointers and indent properly.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    1,625
    As I said ( seems noone reads my posts ), this is how you get if current is a leap year:
    Code:
    bool IsLeapYear(int Year)
    {
        return (!(Year % 4) && (Year % 100)) || !(Year % 400);
    }
    CommonTater likes this.
    Devoted my life to programming...

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. ; problem near if statement
    By orhanli1 in forum C Programming
    Replies: 3
    Last Post: 01-17-2011, 07:42 AM
  2. problem with if statement
    By eagle0eyes in forum C Programming
    Replies: 13
    Last Post: 05-27-2010, 02:12 PM
  3. If Else statement problem
    By doofusboy in forum C Programming
    Replies: 2
    Last Post: 11-09-2005, 07:18 AM
  4. If statement re-do problem
    By RoD in forum Windows Programming
    Replies: 5
    Last Post: 09-11-2002, 05:46 PM
  5. having a problem with a FOR statement
    By jonesy in forum C Programming
    Replies: 3
    Last Post: 10-01-2001, 02:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21