Eat.随 发表于 2023-12-7 16:25:18

解决问题

请问这一题怎么解决?(用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:28:39

这道题目要求你使用C语言来计算今天的年份、日期、小时和分钟。

首先,我们可以使用`time(NULL)`函数获取当前时间对应的秒数。然后,我们假设每年有365天,并且基于给出的日期(3月15日,2011年)来计算今天是一年中的第几天。提示里提到了一天有多少秒,这个信息可以帮助我们计算。

根据上述条件,可以编写如下代码:

#include <stdio.h>
#include <time.h>

// 计算年份和日期
void calculateYearAndDay(time_t seconds, int *year, int *day) {
    // 计算今天是一年中的第几天
    *day = seconds / (24 * 60 * 60) + 83;

    // 计算年份
    *year = 2011 + (*day / 365);
}

// 计算小时和分钟
void calculateHourAndMinute(time_t seconds, int *hour, int *minute) {
    // 计算小时和分钟
    *hour = (seconds % (24 * 60 * 60)) / 3600;
    *minute = (seconds % 3600) / 60;
}

// 打印时间
void printTime(int year, int day, int hour, int minute){
    printf("Today is: %d-%d, Time: %02d:%02d", year, day, hour, minute);
}

int main() {
    time_t currentTime = time(NULL);

    int year, day, hour, minute;

    calculateYearAndDay(currentTime, &year, &day);
    calculateHourAndMinute(currentTime, &hour, &minute);
    printTime(year, day, hour, minute);

    return 0;
}

这段代码首先使用`time(NULL)`函数获取当前时间对应的秒数。然后,调用`calculateYearAndDay`函数计算年份和日期,传入秒数和指向年份和日期变量的指针。接着,调用`calculateHourAndMinute`函数计算小时和分钟,同样传入秒数和指向小时和分钟变量的指针。最后,调用`printTime`函数将计算出的时间打印出来。

注意,这段代码没有考虑闰年的情况。如果你希望正确处理闰年,你需要在`calculateYearAndDay`函数中添加相应的逻辑。

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