按升序输出两个时间值
Output two time values in ascending order
在提示用户输入两个时间值后,我在按升序输出一个类的两个对象(t1和t2)时遇到一些问题。我知道bool和if结构的构造方式有一些错误。任何帮助都将不胜感激!
bool lessthan(Time t2) //For two Time objects t1 and t2, t1.lessthan(t2) returns true if t1 is less than, or comes before t2.
{
if (hours < t2.hours)
{
return true;
}
if (minutes < t2.minutes)
{
return true;
}
if (seconds < t2.seconds)
{
return true;
}
return false;
}
bool greaterthan(Time t2) //For two Time objects t1 and t2, t1.greaterthan(t2) returns true if t1 is greater than, or comes after t2.
{
if (hours > t2.hours)
{
return true;
}
if (minutes > t2.minutes)
{
return true;
}
if (seconds > t2.seconds)
{
return true;
}
return false;
}
bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
if (hours == t2.hours)
{
return true;
}
if (minutes == t2.minutes)
{
return true;
}
if (seconds == t2.seconds)
{
return true;
}
return false;
}
在主要功能中,我有以下代码:
cout << "nTime values entered in ascending order: "<<endl;
if (t1.lessthan(t2))
t1.write();
cout << endl;
t2.write();
cout << endl;
我认为相等的类应该是
bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
if (hours != t2.hours)
{
return false;
}
if (minutes != t2.minutes)
{
return false;
}
if (seconds != t2.seconds)
{
return false;
}
return true;
}
在您的代码中,如果小时是相同的,与分钟和秒无关,那就足够了。在我的版本中,我颠倒了逻辑顺序。
对于比较函数,请尝试:
bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
if (hours == t2.hours && minutes == t2.minutes && seconds == t2.seconds)
{
return true;
}
return false;
}
bool lessthan(Time t2) //For two Time objects t1 and t2, t1.lessthan(t2) returns true if t1 is less than, or comes before t2.
{
if (hours > t2.hours)
{
return false;
}
if (minutes > t2.minutes)
{
return false;
}
if (seconds > t2.seconds)
{
return false;
}
return true;
}
然后根据的其他两个函数实现greaterthan()
greaterthan(Time t2)
{
return (!(equalto(t2) || lessthan(t2));
}
此外,如果你想按升序输出时间,你需要做这样的事情:
cout << "nTime values entered in ascending order: "<<endl;
if (t1.lessthan(t2))
{
t1.write();
cout << endl;
t2.write();
cout << endl;
}
else
{
t2.write();
cout << endl;
t1.write();
cout << endl;
}
对于当前代码,最后3行将始终执行,因为它们与if语句无关。你需要括号。
相关文章:
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 计算两个代码块的时间复杂度
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- Levenshtein 两个文件的距离花费了太多时间
- 以天C++为单位的两个时间戳之间的差异
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 与操作员比较两个计时时间点
- 如何获取两个时间点之间的时间
- 图问题:找出两个节点是否在每个节点的O(1)时间和O(2)存储中共享同一分支
- 添加两个时间值存储为数据库中的字符串
- 如何使用C ++在微秒和纳秒中获取两个时间间隔之间的差异
- 按升序输出两个时间值
- 两个时间之间经过的时间,格式为24小时hh:mm:ss
- 设计一个结构来存储时间和日期.写一个函数来计算两个时间之间的差(以分钟为单位)
- 如何比较格式的两个时间戳"Month Date hh:mm:ss"以检查 +ve 或 -ve 值
- 时间差-两个时间点之间的差,以毫秒为单位
- 在Windows下查找两个时间戳之间的CPU活动
- C++ 使用运算符重载添加两个时间值