Search code examples
c++leap-year

Code - help leapyear


I've got an issue with my code here. The program is supposed to count seconds/year. I've managed to fix the leapyear but couldn't fix the normal year. Hope someone could fix it. (it's a function that's called to main)

Note

  • h=hours
  • d=day
  • ye=year
  • m=month
  • s= seconds
  • t= total seconds
  • t2= leapyear

#include <iostream>
using namespace std;

void max_s()                            
{
    unsigned long long s=1; 

int h=s*60;

    int d=h*24; 
    int m=30; 
    int ye=12;
    long long t=s*h*d*m*ye; 
    long long t2=t+86400;
    bool y,n;
    y=true;
    n=false;
    cout<<"leapyear? 'y' for yes 'n' for no "<<endl;
    cin>>y||n;
    if(y=true)
    {
        cout<<"leapyear:"<<t2<<endl;
    }
    else
    {   
        n=false;
        cout<<t;
        cout<<"seconds/year "<<endl;
    }
}

Solution

  • if(y=true) This is always true since it'll be evaluated to the assigned value.

    Should be:

    if(y)

    Actually this is a very good reason to see why we don't write == true when comparing booleans. You can easily misspell one = causing assignment instead of comparing.

    Furthermore, what exactly is cin>>y||n;?

    Tip that saves lives: As @FredLarson mentioned, enable warnings (-Wall) and you'll get a warning about that.