有人可以向我解释为什么时间会这样运作吗?

标签 c if-statement time calculator

我在这上面花了一个小时,但我无法创建一个适用于我的 c 程序的公式。 (我有一个新程序员)。

我必须将 UTC 时间转换为特定城市的相应时间。除了这里之外,我的代码工作正常。这里它给了我错误的答案。我无法理解它(我创建了一个公式,但它对我来说毫无意义)。

在我的程序中,时间输入为 24 小时制。上午 9 点 = 900、中午 12 点 = 1200、凌晨 12 点 = 0 等等。

如果我们被要求将 2359 转换为 Eucla 时间 (UTC +845),我的程序输出 804。正确答案是 844。 我知道如何计算 844,但我不明白它的意义。

2359 + 845 = 3204 (adding the timezone offset 845 to the UTC time)
3204 - 60 = 3144 (minus 60 for some reason [I followed my time overflow formula]
3144 - 2400 = 2400 (minus 2400 because time cannot be more than 2359)

我的程序如何工作

首先加上 UTC 和偏移时间

calculatedTime = UTC + offset;

然后在下面

if (calculatedTime < 2359) {
calculatedTime = calculatedTime - 2400;
}

我还有另一个函数来检查下面的溢出时间

if (((calculatedTime > 59) && (calculatedTime < 99)) || ((calculatedTime > 159) && (calculatedTime < 199))) {

// All the way to 2359

calculatedTime = calculatedTime - 60 + 100;

}

最佳答案

您需要将时间分为小时和分钟。然后分别将时区偏移量添加到小时和分钟中。处理翻滚。最后,将小时和分钟重新组合成最终答案。

像这样:

int main(void)
{
    // inputs
    int time = 2359;
    int zone =  845;

    // separate hours and minutes
    int timeHours = time / 100;
    int timeMinutes = time % 100;
    int zoneHours = zone / 100;
    int zoneMinutes = zone % 100;

    // add the hours and minutes
    int hours = timeHours + zoneHours;
    int minutes = timeMinutes + zoneMinutes;

    // handle the rollover conditions
    if (minutes > 60) {
        minutes -= 60;
        hours++;
    }
    if (hours > 24) {
        hours -= 24;
    }

    // recombine the hours and minutes
    int adjustedTime = hours * 100 + minutes;
    printf("%d\n", adjustedTime);
}

请注意,此代码仅适用于具有正偏移量的时区。您需要弄清楚如何使其适用于负时区。

关于有人可以向我解释为什么时间会这样运作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726627/

相关文章:

PHP-MYSQL 根据截止日期显示不同的颜色

c - 使用指针将 char 和 float 值从 scanf 返回到主函数 C

c - 无法理解此函数 extern void _setvect1(int vector, _Interrupt1 void (*target)());

用于计算均值、中位数、众数和其他统计数据的 c 库?

python - if else 在 for 循环下工作 != but ==

excel - 按时间间隔运行宏的代码?

java - 相当于 Java 中的 "sizeof() of C"

c - 在 C 中播种 If else 条件

java - 使用数组获取正数

Android: getRelativeTime 示例