简体   繁体   English

正确处理24小时时间

[英]Handling 24 Hour Time Properly

I am writing a C program to take in a value representing a time of the day in 24 hour format, and a time duration in similar format, positive or negative. 我正在编写一个C程序,以一个值表示24小时格式的一天中的某个时间,并以相似的格式(正数或负数)表示持续时间。 This program should calculate the 24 hour time after the duration (that is, beginning + duration = end). 该程序应计算持续时间之后的24小时时间(即开始+持续时间=结束)。 For example, 1345 and 345 would output 1730. 例如,1345和345将输出1730。

However, I have no idea how to handle improper inputs. 但是,我不知道如何处理不正确的输入。 For example, values like 2372 or 2520 shouldn't be accepted. 例如,不应接受2372或2520之类的值。 As well, if I have (for example) 100 and -200, I should get 2300 as output instead of -100. 同样,如果我有(例如)100和-200,则应该得到2300而不是-100。 In short, I know that the first two numbers should be mod 24, and the last two numbers should be mod 60, but I don't know how to apply these operations to the input. 简而言之,我知道前两个数字应为mod 24,而后两个数字应为mod 60,但我不知道如何将这些操作应用于输入。 Can anyone offer any tips on how I can do this? 谁能提供有关我该如何做的任何提示?

Read the input as an int , separate the minutes from the hours and check both of them: 将输入读取为int ,将分钟和小时分开,并检查它们两者:

int tm, h, m, is_negative = 0;
scanf("%d", &tm);

if (tm < 0) {
    is_negative = 1;
    tm = -tm;
}

m = tm % 100; // separates the two last digits
h = tm / 100; // excludes the two last digits

if (m > 59) {
    handle_error();
}

if (h > 23) {
    handle_error();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM