Comp Sci Solving C++ Leap Year Program: An Overview

  • Thread starter Thread starter lkh1986
  • Start date Start date
  • Tags Tags
    C++ Program Year
AI Thread Summary
The discussion focuses on creating a C++ program to determine if a year is a leap year. The initial code contains errors, particularly the use of "if (value==int)", which is incorrect. Participants suggest using the modulus operator (%) to check if the year is divisible by 4, which is essential for leap year calculations. Additionally, they note that the rules for leap years are more complex than just being divisible by 4, referencing external resources for further clarification. The conversation emphasizes the importance of understanding the modulus operator in C++.
lkh1986
Messages
96
Reaction score
0

Homework Statement


I just started my C++ courses and here is my question.



Homework Equations





The Attempt at a Solution


//This program states whether a given year is a leap year or a non-leap year.

#include <iostream.h>
#include <conio.h>

void main ()
{
int year, value;
char answer,y, n;

while (answer == y)
{
cout << "Please input a year: ";
value = year/4;
if (value==int)
cout << ""<< year << " is a leap year. There are 29 days in Feb " << year <<".";
else
cout << ""<< year << " is a non-leap year. There are 28 days in Feb " << year <<".";
}
cout << "Do you want to continue? Press 'y' if yes or 'n' if no.";
getch();
}

It seems that "if (value==int)" is illegal. Is there any other way I can put th expression statement so that the computer can print out whether a given year is a leap year or not?

Thanks.
 
Physics news on Phys.org
What you need to do is to check if the variable year is a multiple of 4 and the modulus operator % is perfect for the task, e.g.,
1%4 = 1, 2%4 = 2, 3%4 = 3, 4%4 = 0, 5%4 = 1, ...

What should the conditional expression be for the if-statement now then?

Btw, the rules for checking a leap year is a bit more involved than the above. Look http://en.wikipedia.org/wiki/Leap_year" for an insight.
 
Last edited by a moderator:
Okay, thanks for the help. My instructor just introduced the modulus operator today.
 

Similar threads

Replies
3
Views
1K
Replies
2
Views
3K
Replies
7
Views
7K
Replies
9
Views
2K
Replies
3
Views
1K
Replies
5
Views
2K
Replies
15
Views
3K
Replies
14
Views
4K
Back
Top