I am trying to write a simple program in c++ that returns the day of the week for a given date.
The input format is day, month, year. I cannot get it to work with leap years. I tried subtracting one from the a
variable when the input year is a leap year, but the program just ends up crashing without an error message.
I would appreciate any suggestions, but please try to remain simple, I am still a beginner. Apologies for the stupid question, and please excuse my mistakes, this is the first time I post on this site.
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
int d;
int m;
int y;
string weekday(int d, int m, int y){
int LeapYears = (int) y/ 4;
long a = (y - LeapYears)*365 + LeapYears * 366;
if(m >= 2) a += 31;
if(m >= 3 && (int)y/4 == y/4) a += 29;
else if(m >= 3) a += 28;
if(m >= 4) a += 31;
if(m >= 5) a += 30;
if(m >= 6) a += 31;
if(m >= 7) a += 30;
if(m >= 8) a += 31;
if(m >= 9) a += 31;
if(m >= 10) a += 30;
if(m >= 11) a += 31;
if(m == 12) a += 30;
a += d;
int b = (a - 2) % 7;
switch (b){
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
}
}
int main(){
cin >> d >> m >> y;
cout << weekday(d, m, y);
}
y
is already an int. Consequently the cast(int) y/ 4
is redundant, and(int)y/4 == y/4
is always true – Extensile(int) (y/4) == y/4
– Reams