my homework is in c. program:check if user's input is not leap year then find the nearest leap year to user's input. variable:y 1300<y<1400
I think the best way is to write it with while loop like.
#include <stdio.h>
int main()
{
int year;
scanf("%d", &year);
while(1300<year<1400)
{
if (year % 100 == 0)
{
//i don't know:(
}
}
return 0;
}
CodePudding user response:
How I would solve this :
#include <stdio.h>
int main()
{
int year;
int moreyear;
int lessyear;
scanf("%d", &year);
moreyear= year; // Different var to avoid the cases where the incremented year goes after 1400 while there are leap years before to search
lessyear = year; // Here to check if a year before is leap before a year after
while (1300 < year && year < 1400)
{
if (moreyear % 4 == 0 && moreyear % 100 != 0 && moreyear < 1400)
{
printf("%d is leap !", moreyear);
return 0; // stops the program as soon as the year is found
}
else if (lessyear % 4 == 0 && lessyear % 100 != 0 && lessyear > 1300) // I don't know if the leap year must be after 1300 but then, you can add another condition with && lessyear > 1300
{
printf("%d is leap !", lessyear);
return 0; // stops the program as soon as the year is found
}
moreyear ;
lessyear--;
}
printf("No leap year found =("); // This case would be surprising if user entered a year between the interval
return 0;
}
CodePudding user response:
First of all, the task is invalid, since the Gregorian calendar wasn't in use between 1300 and 1400 BCE. But let's ignore that...
So, you need to remind yourself of a proper rule for determining if a year is a leap year or not:
In the Gregorian calendar, three criteria must be taken into account to identify leap years:
- The year must be evenly divisible by 4.
- If the year can also be evenly divided by 100, it is not a leap year;
- Unless the year is also evenly divisible by 400. Then it is a leap year.
(Taken from here)
Now, I suggest you write a function which, given a year, returns true
if it's a leap year and false
otherwise. It's usually a good idea, once you've defined a piece of your computation with distinct inputs and outputs, to separate it out into a function, rather than write everything within a single large main program.
Finally, use the function in the loop in your main program. Note that, as @stark points out, you can't write the loop the way that you have, i.e. C doesn't support a lower_bound < variable < upper_bound
notation like we're used to from continued math equations; you have to separate that into two expressions with a logical "and": (lower_bound < variable) && (variable < upper_bound)
.
Also, since you're just iterating through all year, you might want to consider a for loop:
for(int year = 1301; year < 1400; year ) {
// do things with year
}