我在这上面花了一个小时,但我无法创建一个适用于我的 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/