C++时间计算器负数值问题求助:无if语句下的修正方案
问题解决思路
你的问题出在时间相减得到负数时,直接计算会输出负的小时和分钟,而我们需要的是前一天的对应时间。按照作业提示,不用if语句的话,可通过算术运算给差值加上足够多的一天分钟数(24*60=1440),再取模1440,把负数转换为合法的正数时间值。
修正后的代码
#include <iostream> #include <string> #include <iomanip> using namespace std; int run() { cout << "Give me a time (such as 3:57) and a duration" << endl; cout << "(such 1:05), and will tell you the sum" << endl; cout << "(that is the time that follows the given time" << endl; cout << "by the given duration), and difference (the time that proceeds the given time by that duration)." << endl; cout << "Time: " << endl; int timeHours; int timeMinutes; char discard; cin >> timeHours >> discard >> timeMinutes; cout <<"Duration: " << endl; int durationHours; int durationMinutes; cin >> durationHours >> discard >> durationMinutes; int time = timeHours * 60 + timeMinutes; int duration = durationHours * 60 + durationMinutes; int after = time + duration; // 核心修改:加两天分钟数后取模1440,确保结果为0-1439的正数 int before = (time - duration + 1440 * 2) % 1440; int afterHours = (after / 60) % 12; int afterMinutes = after % 60; int beforeHours = (before / 60) % 12; int beforeMinutes = before % 60; cout << endl; cout << durationHours <<":" << durationMinutes << " hours after and before, " << timeHours << ":" << timeMinutes << " is [" << ((afterHours + 12) % 12) << ":" << setw(2) << setfill('0') << afterMinutes << ", " << ((beforeHours + 12) % 12) << ":" << setw(2) << setfill('0') << beforeMinutes << "]" << endl; return 0; }
关键修改说明
修正
before的计算:
原代码int before = time - duration;会得到负数,改为(time - duration + 1440 * 2) % 1440。加两天的分钟数是为了覆盖时长超过一天的极端情况,取模1440后结果必然落在0-1439之间,对应一天内的合法分钟数。修正12小时制显示逻辑:
用((hours +12)%12)的算术运算替代条件判断,确保0小时(即12点)能正确显示为12,同时其他小时数保持12小时制的格式,完全符合作业“不能使用if语句”的要求。
测试你给出的案例:输入时间1:18(78分钟),时长10:39(639分钟),计算before为(78-639+2880)%1440=2319%1440=879分钟,879/60=14小时,14%12=2,分钟879%60=39,最终输出2:39,符合预期。
内容的提问来源于stack exchange,提问作者Besco
相关产品推荐
相关产品推荐

