c 给定日期的星期几

新手上路,请多包涵

我正在尝试用 C++ 编写一个简单的程序,它返回给定日期的星期几。

输入格式为日、月、年。我无法让它与闰年一起工作。当输入年份是闰年时,我尝试从 a 变量中减去一个,但程序最终崩溃而没有错误消息。

我会很感激任何建议,但请尽量保持简单,我仍然是初学者。为愚蠢的问题道歉,请原谅我的错误,这是我第一次在这个网站上发帖。

 #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);
}

原文由 OerllydSaethwr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

尝试使用 CTime 类

示例:

 const CTime currTime = CTime::GetCurrentTime();
const int nWeekDay = currTime.GetDayOfWeek();

switch (nWeekDay)
{
    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";
}

在上面的示例中,我使用的是当前时间,但您可以使用不同的方式,使用您想要的时间示例:

 const CTime currTime = CTime(year,month, day, hours, minutes, seconds );

原文由 Adeilson Dos Santos Pastiuk 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题