输入提示询问开始时间,然后询问持续时间,返回两次:一次是相加,一次是相减。我已经掌握了它们的基本知识,但是当我尝试在某些时间(例如1:18和10:39)进行操作时,会得到一个错误消息:
X Input of 1:18 10:39 : expected [11:57, 2:39] but found [11:57, -9:-21]
以下是进行计算的代码:
int timeHours, timeMinutes, durHours, durMinutes;
cout << " Time: ";
cin >> timeHours;
cin.get();
cin >> timeMinutes;
cout << " Duration: ";
cin >> durHours;
cin.get();
cin >> durMinutes;
int time, duration, after, before, afterHours, afterMinutes, beforeHours, beforeMinutes;
const int MINUTES_IN_DAY = 60 * 24;
time = (timeHours * 60) + timeMinutes;
duration = (durHours * 60) + durMinutes;
after = time + duration;
before = time - duration;
afterHours = after / 60 % 12;
afterMinutes = after % 60;
beforeHours = before / 60;
beforeMinutes = before % 60;
cout << endl;
cout << durHours << ":" << setfill('0') << setw(2) << durMinutes << " hours after, and before, "
<< timeHours << ":" << timeMinutes << " is [" << afterHours << ":" << setw(2) << afterMinutes << ", "
<< beforeHours << ":" << setw(2) << beforeMinutes << "]" << endl;
上面的失败测试显示总和(1:18 + 10:39)有效,但差(1:18-10:39)不起作用。它给了我“ -9:-21”,应该可以通过增加24小时来解决,这甚至是我的作业所建议的:“这可以很容易地通过在计算时加上前一天(或两到三天)来完成差异”,但是当我在“之前”初始化中添加1440(60 * 24)时:
before = (time - duration) + MINUTES_IN_DAY;
,将分钟数恢复为正常时间,我得到14:39,即2:39,但以24小时制而不是12小时制(顺便说一句,这也使所有通过的其他测试现在都失败了)。我认为当它说“通过增加一天(或两到三天),因为1440与1440 * 2或* 3明显不同,但有一些提示,但是我没有看到它,我必须丢失一些明显的东西。我知道我也必须在午夜之前修复它,但稍后再更改。如果有人知道我要解释的内容,我将非常感激
答案 0 :(得分:0)
(如你建议增加MINUTES_IN_DAY)解决了负值问题,你可以使用%MINUTES_IN_DAY避免因添加MINUTES_IN_DAY为正值溢出
before = ((time - duration)+MINUTES_IN_DAY)%MINUTES_IN_DAY;
答案 1 :(得分:0)
通常,在处理时间/日期时,使自己具有将人类可读的日期转换为毫秒或秒(反之亦然)并以此为基础进行构建的功能会更容易。就您而言,您只需在几秒钟内添加/减去两个时间标记即可:
long long time = toSec(timeHours, timeMinutes, timeSeconds);
long long duration = toSec(durHours, durMinutes, durSeconds);
string after = toDate(time + duration);//somethig like 12:34:00 (hh:mm:ss)
string before = toDate(time - duration);
然而,投入的努力在制造这样的转换函数将是一个overcomplication如果你使用它们是一次性计算。