[英]Can someone explain to me why time is working like this?
我在此上花了很長時間,但無法創建適用於我的c程序的公式。 (我有一個新的程序員)。
我必須將UTC時間轉換為特定城市的時間。 除了這里,我的代碼運行完美。 這給了我錯誤的答案。 我無法解決這個問題(我創建了一個公式,但對我來說沒有意義)。
在我的程序中,時間輸入為24小時制。 9AM = 900、12PM = 1200、12am = 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);
}
請注意,此代碼僅適用於具有正偏移量的時區。 您需要弄清楚如何使其在負時區工作。
OP的代碼有各種一次性錯誤。
// if (((calculatedTime > 59) && (calculatedTime < 99)) ||
// ((calculatedTime > 159) && (calculatedTime < 199))) {
if (((calculatedTime > 59) && (calculatedTime < 100)) ||
((calculatedTime > 159) && (calculatedTime < 200))) {
// if (hours > 24) {
// hours -= 24;
// }
if (hours >= 24) {
hours -= 24;
}
也碼具有使用類似的值更清晰60, 100
if (((calculatedTime >= 60) && (calculatedTime < 100)) ||
((calculatedTime >= 60*2) && (calculatedTime < 100*2))) {
然而,OP的方法失敗了,因為負數。
要處理正負時間值,請將“ hhmm”時間分為幾個小時和幾分鍾。 尋找“分鍾”溢出的條件。 我建議使用2個輔助函數來拆分和合並結果。
#include <stdio.h>
#include <stdlib.h>
void hhmm_split(int hhmm, int *hour, int *min) {
*hour = hhmm / 100;
*min = hhmm % 100;
}
/* `min` may be outside the primary range of (-60 ... 60) */
int hhmm_combine(int hour, int min) {
hour += min / 60;
min %= 60;
if (hour < 0 && min > 0) {
min -= 60;
hour++;
} else if (hour > 0 && min < 0) {
min += 60;
hour--;
}
hour %= 24;
return hour * 100 + min;
}
測試碼
void hhmm_add(int t1, int t2) {
int t1_hh, t1_mm, t2_hh, t2_mm;
hhmm_split(t1, &t1_hh, &t1_mm);
hhmm_split(t2, &t2_hh, &t2_mm);
int sum = hhmm_combine(t1_hh + t2_hh, t1_mm + t2_mm);
printf("t1:% 05d + t2:% 05d = sum:% 05d\n", t1, t2, sum);
}
int main(void) {
hhmm_add(2359, 845);
hhmm_add(2359, -845);
hhmm_add(-2359, 845);
hhmm_add(-2359, -845);
}
輸出:
t1: 2359 + t2: 0845 = sum: 0844
t1: 2359 + t2:-0845 = sum: 1514
t1:-2359 + t2: 0845 = sum:-1514
t1:-2359 + t2:-0845 = sum:-0844
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.