gpt4 book ai didi

c - 如何获得正确的时间

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

#include <stdio.h>
// this creates the structure
struct time
{
int hour;
int minute;
int second;
};

//function that calculates the time

struct time timeUpdate(struct time now)
{

now.second = now.second + 1;

if (now.second == 60)
{
now.second = 0;
now.minute = now.minute + 1;

if (now.minute == 60)
{
now.minute = 0;
now.hour = now.hour + 1;
}
if (now.hour = 60)
{
now.hour = 0;
}
}
return now;
}

//user input and output
int main(void)
{
struct time currentTime, nextTime;

printf("Please enter the current time: ");
scanf("%i:%i:%i\n", &currentTime.hour, &currentTime.minute, &currentTime.second);

nextTime = timeUpdate(currentTime);

printf("%.2i:%.2i:%.2i\n", nextTime.hour, nextTime.minute, nextTime.second);

return 0;
}

最佳答案

假设您的输入有效(0 <= 小时 <= 23 && 0 <= 分钟 <= 59 && 0 <= 秒 <= 59),以下是我的观察结果:

  • 在 timeUpdate 中你说 now.hour = 60。你必须检查 now.hour 是否等于 24(if (now.hour == 24))你的函数应该是这样的:

    now.second = now.second + 1;

    if (now.second == 60)
    {
    now.second = 0;
    now.minute = now.minute + 1;

    if (now.minute == 60)
    {
    now.minute = 0;
    now.hour = now.hour + 1;

    if (now.hour == 24)
    {
    now.hour = 0;
    }
    }
    }

    return now;
  • 我从 scanf 中删除了 '\n',因为我很困惑为什么程序不显示结果(我必须写一个字符并按 Enter 键才能看到结果)。现在该行看起来像这样 scanf("%i:%i:%i", &currentTime.hour, &currentTime.minute, &currentTime.second);

关于c - 如何获得正确的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943936/

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