#include <iostream>
#include <string>
using namespace std;
void dayofweek(int &m, int d, int y);
int main()
{
int m, d, y, daynum;
char ans;
do {
cout << "Enter a date as mm dd yyyy: \n";
cin >> m >> d >> y;
dayofweek(m, d, y);
cout << m << d << y;
daynum=(d + 5 + ((26*(m+1))/10) + ((5*(y%100))/4) + ((21*(y/100))/4) )%7;
cout << daynum;
switch(daynum)
{
case 0:
cout << m << "/" << d << "/" << y << "is a Monday \n";
break;
case 1:
cout << m << "/" << d << "/" << y << "is a Tuesday \n";
break;
case 2:
cout << m << "/" << d << "/" << y << "is a Wednesday \n";
break;
case 3:
cout << m << "/" << d << "/" << y << "is a Thursday \n";
break;
case 4:
cout << m << "/" << d << "/" << y << "is a Friday \n";
break;
case 5:
cout << m << "/" << d << "/" << y << "is a Saturday \n";
break;
case 6:
cout << m << "/" << d << "/" << y << "is a Sunday \n";
break;
}
cout<<"Do you want to continue? (y/n) \n";
cin >> ans;
}while (ans == 'y' || 'Y');
return 0;
}
void dayofweek(int& m, int d, int y)
{
if (m==1 || m==2)
m=m+12;
}
这编译并且工作正常,但是当我输入日期时,会出现错误的工作日。
例如,2014年2月28日是星期五,但周六出现。 有什么建议?我坚持要改变什么,我也多次检查方程式。
答案 0 :(得分:1)
在Zeller的同意实施结果中意味着:0 = Saturday, 1 = Sunday, 2 = Monday
......
您使用的公式还需要更改dayofweek
函数和更改以处理年份。我决定抛弃dayofweek
函数而不是介绍dayNumber
。
将此更改应用于切换语句和函数后,我得到January 1, 2000
和March 1, 2000
的{{3}}示例的正确结果。另外,对于2 28 2014
输入,我得到Friday
作为正确答案。
更改了代码:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int dayNumber(int m, int d, int y) {
if (m == 1 || m == 2) {
m = m + 12;
y = y - 1;
}
return (d + (int)floor((13 * (m + 1)) / 5) + y%100 + (int)floor((y%100)/ 4) + (int)floor(((int)floor(y/100))/4) + 5*(int)floor(y/100)) % 7;
}
int main() {
int m, d, y, daynum;
char ans;
do {
cout << "Enter a date as mm dd yyyy: \n";
cin >> m >> d >> y;
daynum = dayNumber(m, d, y);
cout << "daynum:" << daynum << "\t";
switch (daynum) {
case 2:
cout << m << "/" << d << "/" << y << " is a Monday \n";
break;
case 3:
cout << m << "/" << d << "/" << y << " is a Tuesday \n";
break;
case 4:
cout << m << "/" << d << "/" << y << " is a Wednesday \n";
break;
case 5:
cout << m << "/" << d << "/" << y << " is a Thursday \n";
break;
case 6:
cout << m << "/" << d << "/" << y << " is a Friday \n";
break;
case 0:
cout << m << "/" << d << "/" << y << " is a Saturday \n";
break;
case 1:
cout << m << "/" << d << "/" << y << " is a Sunday \n";
break;
}
cout << "Do you want to continue? (y/n) \n";
cin >> ans;
} while ((ans == 'y') || (ans == 'Y'));
return 0;
}