i have a problem regarding functions. this leap year code is frustrating because it will always give me "not a leap year" whenver i entered a year:

#include <iostream>
using namespace std;

int get_input();
bool CheckLeapYear(int);

int main()
{
    int year,x;
    char key;

  do {
      year=get_input();
      cout<<CheckLeapYear(x)<<endl;

      cout<<"Press 'y' to continue: ";
      cin>>key;
      
      }
      while (key=='Y' || key=='y');
      
  system("pause");
  return 0;
}

int get_input()
{
    int x;
    cout<<"\nPlease enter a year : ";
    cin>>x;
    return x;
}

bool CheckLeapYear(int x)
{
    if (x % 400==0 || x % 4==0 && x % 100!=0)
    cout<<"\nThe year is a leap year\n"<<endl;
    
    else
    cout<<"\nThe year is a not leap year\n"<<endl;
    
}

and if you run it, theres a 192 value and i don't even know where does it comes from...teach me something about functions.....help me please...and please don't give me direct answer, i need to learn functions....

Recommended Answers

All 4 Replies

Not sure if you are getting the error (still getting back into C++ from a long spell in Python), but I think you need to define your "get_input" and "CheckLeapYear" functions before the main. Otherwise, you are calling something from the main that is not yet initialized. It also helps to keep the same type format for your function names. "get_input" and "CheckLeapYear" could instead become "GetInput" and "CheckLeapYear", or "get_input" or "check_leap_year".

I did a quick google for this problem and it seems that your logic for working out whether "x" is a leap year or not may be wrong. This is a line of C code I found:

if(year%400 ==0 || (year%100 != 0 && year%4 == 0))

Hope this helps you out :)

hey, thanx, the logic is working..but the value 192 still appears

fix it, i've shouldn't cout the function checkleapyear in the main. just gotta put the function without cout...thnx mate this thread is solved and here's the code :

#include <iostream>
using namespace std;

int get_input();
bool CheckLeapYear(int);

int main()
{
    int year;
    char key;

  do {
      year=get_input();
      CheckLeapYear(year);
      cout<<"Press 'y' to continue: ";
      cin>>key;
      
}
      while (key=='Y' || key=='y');
      
  system("pause");
  return 0;
}

int get_input()
{
    int x;
    cout<<"\nPlease enter a year : ";
    cin>>x;
    return x;
}

bool CheckLeapYear(int year)
{
    if(year%400 ==0 || (year%100 != 0 && year%4 == 0))
    cout<<"\nThe year is a leap year\n"<<endl;
    
    else
    cout<<"\nThe year is a not leap year\n"<<endl;    
}

Nice. Can you upvote my post seeing as it helped you?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.