gpt4 book ai didi

c - 返回星期几并提供日、月、年和一月一日?

转载 作者:行者123 更新时间:2023-11-30 21:34:59 25 4
gpt4 key购买 nike

我的C99如下:

int dayOfWeek(int 日、int 月、int 年、int firstJan);

第一个参数 day,提供感兴趣的日期 - 范围从 1 到 31(含)。第二个参数,月份,提供感兴趣的月份 - 范围从 1 到 12(含)。第三个参数,年份,提供感兴趣的年份 - 1970 或更大的任何整数值。第四个参数,firstJan,表示所提供年份中一月一日是星期几。

该函数将返回指定日期所在的星期几。例如调用:

dayOfWeek(13, 11, 2017, 0);

将返回整数1(代表星期一)。

我该如何解决这个问题?其允许值为 0(代表星期日)、1(代表星期一)等,最多为 6(代表星期六)。代码已编辑:

  1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int dayOfweek(int day, int month, int year, int firstJan)
5 {
6 int mth[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
7 int mth_leap[] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
8
9 if(year <1970 || month < 1 || month > 12 || day < 1 || day > 31 || firstJan < 0 || firstJan > 6 ){
10 printf("invalid input");
11 //return -1;
12 }
13
14 if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)){
15 day = mth_leap[month - 1] + day ;
16 }else{
17 day = mth[month - 1] + day;
18 }
19
20 int dow = (day - firstJan + 7)%7;
21 printf("Day of week is %i.\n", dow);
22 //return 1;
23
24 }

最佳答案

只需使用mktime()即可找到星期几。

mktime 函数

On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time,

#include <time.h>

int dayOfWeek(int day, int month, int year, int /*firstJan*/) {
// struct tm members domain are: years from 1900, and months since January
// Important to set tm_isdst = -1 to let the function determine dst setting.
struct tm ymd = { .tm_year - 1900, .tm_mon = month - 1, .tm_mday = day, .tm_isdst = -1);

time_t t = mktime(&ymd); // this will fill in .tm_wday
if (t == -1) return -1; // Failed to find a valid calender time (and day-of-the-week)
return ymd.tm_wday;
}
<小时/>

How can I approach the solution?

但是 OP 有一个函数可以提供 1 月 1 日是星期几。

该方法的一些伪代码:

int dayOfWeek(int day, int month, int year, int firstJan) {
days_since_jan1 = table[month] + day;
if (month > Feb and isleap(year)) days_since_jan1++;
dow = (days_since_jan1 - firstJan + 7)%7
}

关于c - 返回星期几并提供日、月、年和一月一日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com