增加和减去时间
Adding and Subtracting Time
我是C 的新手 - 我想使用HH:MM格式来添加和减去时间。样本输入:
12:00 + 3:00 - 6:00
样本输出:
9:00
另一个样本输入:
9:00 + 8:00 + 13:00 - 2:25
样本输出:
27:35
我该如何了解?我当时认为将所有内容转换为几秒钟,然后应用数学,然后使用模量60函数返回时间。构建这样的程序有任何帮助吗?
您需要考虑'时间'的含义。有两个概念,时间点和持续时间。将时间点添加在一起没有任何意义。添加和减去持续时间(导致持续时间)确实很有意义,并且在时间点增加和减去持续时间(导致与原始的新时间点偏移)是有意义的。从另一个时间点减去一个时间点,产生中间持续时间也很有意义。
很多时候API在这两个概念之间区分区别不佳,但是标准C <chrono>
库会。
这是一些滥用C tm
类型的代码,以便从用户那里获得几个持续时间,将它们添加在一起,然后再次滥用tm
以输出结果。
#include <iostream> // cout, cin
#include <iomanip> // get_time, put_time
#include <chrono> // hours, minutes, duration_cast
int main() {
// input, get a couple durations to do arithmetic on
// technically std::tm represents a time point and get_time is supposed to
// parse a time point, but we treat the results as a duration
std::tm t;
std::cin >> std::get_time(&t, "%H:%M");
auto duration1 = std::chrono::hours(t.tm_hour) + std::chrono::minutes(t.tm_min);
std::cin >> std::get_time(&t, "%H:%M");
auto duration2 = std::chrono::hours(t.tm_hour) + std::chrono::minutes(t.tm_min);
// do the arithmetic
auto sum = duration1 + duration2;
// output
auto hours = std::chrono::duration_cast<std::chrono::hours>(sum);
auto minutes = std::chrono::duration_cast<std::chrono::minutes>(sum - hours);
t.tm_hour = hours.count();
t.tm_min = minutes.count();
std::cout << std::put_time(&t, "%H:%M") << 'n';
}
我想共享一些代码,因为问题要求将程序作为c 的新手。这不是完美的代码,但对于新手C 的人来说可能是一个很好的动手。它将解决时间戳记的加法和减法。即,您可能需要添加其他验证,并且可以扩展到代表天数,秒和毫秒...
#include <iostream>
#include <string>
using namespace std;
/// Represents the timestamp in HH:MM format
class Time {
public:
// Construct the time with hours and minutes
Time(size_t hours, size_t mins);
// Construct the time using a string
Time(const string& str);
// Destructor
~Time() {}
// Add a given time
Time operator + (const Time& rTime) const;
// Subtract a given time
Time operator - (const Time& rTime) const;
// Get the members
int Hours() const { return m_Hours; }
int Minutes() const { return m_Minutes; }
// Get the time as a string in HH:MM format
string TimeStr();
private:
// Private members
int m_Hours; // Hours
int m_Minutes; // Minutes
};
// Constructor
Time::Time(size_t hours, size_t mins) {
if (hours >= 60 || mins >= 60) {
cout << "Invalid input" << endl;
exit(0);
}
// Update the members
m_Hours = hours;
m_Minutes = mins;
}
// Add the given time to this
Time Time::operator + (const Time& rTime) const {
// Construct the time
int nTotalMinutes(m_Minutes + rTime.Minutes());
int nMinutes(nTotalMinutes % 60);
int nHours(nTotalMinutes/60 + (m_Hours + rTime.Hours()));
// Return the constructed time
return Time(nHours, nMinutes);
}
// Construct the time using a string
Time::Time(const string& str) {
if(str.length() != 5 || str[2] != ':') {
cout << "Invalid time string. Expected format [HH:MM]" << endl;
exit(0);
}
// Update the members
m_Hours = stoi(str.substr(0, 2));
m_Minutes = stoi(str.substr(3, 2));
}
// Substact the given time from this
Time Time::operator - (const Time& rTime) const {
// Get the diff in seconds
int nDiff(m_Hours*3600 + m_Minutes*60 - (rTime.Hours()*3600 + rTime.Minutes()*60));
int nHours(nDiff/3600);
int nMins((nDiff%3600)/60);
// Return the constructed time
return Time(nHours, nMins);
}
// Get the time in "HH:MM" format
string Time::TimeStr() {
// Fill with a leading 0 if HH/MM are in single digits
return ((m_Hours < 10) ? string("0") + to_string(m_Hours) : to_string(m_Hours))
+ string(":")
+ ((m_Minutes < 10) ? string("0") + to_string(m_Minutes) : to_string(m_Minutes));
}
int main() {
Time time1("09:00"); // Time 1
Time time2("08:00"); // Time 2
Time time3("13:00"); // Time 3
Time time4("02:25"); // Time 4
//time1 + time 2 + time3 - time4
cout << (time1 + time2 + time3 - time4).TimeStr() << endl;
return 0;
}
输出:27:35
this(第1部分),此(第2部分)应该是恰好您想要的..
您得到了一个明确的解释,作者逐行遍历代码,他还使用最佳实践。
最简单的解决方案只是将输入分解为整数(使用std::istream
),将它们插入tm
(在<time.h>
中定义),然后调用mktime
(也在<time.h>
中)。(在C 11中有一些新内容,但我还不熟悉它。)
我在这一行中发现了一个小问题:
int nDiff(m_Hours*3600 + m_Minutes*60 - (rTime.Hours()*3600 + rTime.Minutes()*60));
在ndiff(...)中,参数必须是绝对值!ndiff(abs(...))
例如:
Time time1("01:00");
Time time2("02:00");
cout << ( time1 - time2 ).TimeStr() << endl;
输出:
hours = 18446744073709551615
Invalid input
案例:
cout << ( time1 + time2 ).TimeStr() << endl;
输出:
03:00
这个结论只是改变:
int nDiff(m_Hours*3600 + m_Minutes*60 - (rTime.Hours()*3600 + rTime.Minutes()*60));
为此:
int nDiff( abs(m_Hours*3600 + m_Minutes*60 - (rTime.Hours()*3600 + rTime.Minutes()*60) ) );
并将其添加为代码中的标题:
#include <cstdlib> // function abs()
这样,代码可以很好地工作。:)
愉快的编码!欢呼。
- 我的 c++ 应用程序中的运行时间从 0 增加到 60 太快了(例如一毫秒或一微秒)
- 我看到将我的类成员函数指定为内联实际上会增加执行时间,即使函数体非常小
- 霓虹灯增加了运行时间
- Incredibuild大大增加了链接时间
- 为什么未达到的 try-catch 块会增加运行时时间
- 为什么内存访问时间远远超过CPU缓存大小时会增加
- std::嵌入增加的链接时间
- 使用OpenMP库,执行时间如何取决于线程数量的增加
- C :从一定的时间戳启动计时器,然后将其增加
- 增加和减去时间
- 为什么要在我的OpenMP代码中增加执行时间
- MPI:输出时间随着处理器数量的增加而增加
- 将项目添加到 QListWidget 增加设计时间
- Cocos2D BezierBy 随着时间的推移而增加速度
- 使用 list::size() 后运行时间显著增加
- 使用大型数组索引增加访问时间
- 程序的内存使用量随着时间的推移而增加,但内存泄漏工具报告没有问题
- C++ COM 服务器内存使用量随着时间的推移而增加 - 使用 WinDBG 的分析
- 为什么更改循环迭代顺序会增加运行时间
- 将某个时间增加一天