Eat.随 发表于 2023-12-7 16:51:36

问题求助

请问这一题怎么解决?(用c语言)(并解决闰年的问题)
9.2. Exercise
Calling time (NULL) gives you a large integer. Use this value to calculate today's year, date, hours, and minutes.
  Simplifying assumption:we pretend that each year has exactly365 days. The 15th of March is therefore day 83 in year 2011. (use that date to figure out today's "day number")(hint: how many seconds are there in a day?)
You cannot use struct for this assignment.
You cannot use any time-based functions from the standard library such asasctime or strftime.
  You must use one function to calculate the year and day(pass inthe total seconds, and a reference to the year and day).
  You must use a separate function to calculate the hours andminutes.(again, pass the total seconds, and a reference to the hours and minutes)
  You must use a separate function to print the time; this functioncan only take as arguments the year, day, hour, and minutes.
       handle leap-years correctly, and print the month as well.

FishC_GPT 发表于 2023-12-7 16:59:46

首先,对于计算年份和日期,我们可以使用以下方法:

1. 获取当前时间的总秒数:
   time_t currentTime = time(NULL);

2. 计算今天是一年中的第几天:
   int dayOfYear = ((currentTime / 60) / 60) / 24;

3. 计算今年的年份:
   int currentYear = 2011 + dayOfYear / 365;

4. 计算月份:
   int month;
   if (dayOfYear >= 0 && dayOfYear < 31)
       month = 1;
   else if (dayOfYear >= 31 && dayOfYear < 59)
       month = 2;
   else if (dayOfYear >= 59 && dayOfYear < 90)
       month = 3;
   // 其他月份省略...

5. 计算日期:
   int dayOfMonth;
   switch (month) {
   case 1:
       dayOfMonth = dayOfYear + 1;
       break;
   case 2:
       dayOfMonth = dayOfYear - 30;
       break;
   case 3:
       dayOfMonth = dayOfYear - 58;
       break;
   // 其他月份省略...
   }

接下来,我们来处理小时和分钟的计算。我们需要一个函数来计算这个时间段中的小时和分钟数。代码示例如下:

void calcHoursMinutes(int totalSeconds, int* hours, int* minutes) {
    *hours = (totalSeconds/ 3600) % 24;
    *minutes = (totalSeconds / 60) % 60;
}

最后,我们需要编写一个函数来打印时间。代码示例如下:

void printTime(int year, int month, int day, int hour, int minute) {
    printf("当前时间:%d年%d月%d日 %d时%d分\n", year, month, day, hour, minute);
}

至于闰年的问题,可以使用以下方法进行判断:

int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
      return 1;
    else
      return 0;
}

在计算年份时,可以考虑闰年对天数的影响,例如2月份有28或29天。

希望这些代码对你有帮助!

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 问题求助