如何比较两个小时并说哪个更晚或更早
How to compare two hours and say which one is later or earlier?
如何比较两个小时?我尝试使用下面的代码,但它给了我两次true
,但它应该给出false
和true
:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
bool earlierEqual(int h1, int m1, int s1, int h2, int m2, int s2)
{
if(h1 <= h2)
{
return true;
}
else
{
if(m1 <= m2)
{
return true;
}
else
{
if(s1 <= s2)
{
return true;
}
else
return false;
}
}
}
bool laterEqual(int h1, int m1, int s1, int h2, int m2, int s2)
{
if(h1 >= h2)
{
return true;
}
else
{
if(m1 >= m2)
{
return true;
}
else
{
if(s1 >= s2)
{
return true;
}
else
return false;
}
}
}
int main()
{
int h1 = 12, m1 = 4, s1 = 29;
int h2 = 11, m2 = 12, s2 = 1;
// false
cout << earlierEqual(h1, m1, s1, h2, m2, s2) << "n";
// true
cout << laterEqual(h1, m1, s1, h2, m2, s2) << "n";
return 0;
}
仅当小时数相等时,才应激活else
分支。否则,即使小时h1
大于小时h2
,分钟数的比较也将决定。应将代码更改为以下内容:
bool earlierEqual(int h1, int m1, int s1, int h2, int m2, int s2)
{
if (h1 < h2)
{
return true;
}
else if (h1 == h2)
{
if (m1 < m2)
{
return true;
}
else if (m1 == m2)
{
if (s1 < s2)
{
return true;
}
}
}
return false;
}
如果小时相等,则必须检查分钟,如果这些小时相等,则必须检查秒。仅当条件较少时,才能立即返回 true。这同样适用于第二个功能:只有当更大时,您才能提前返回。
在进行比较之前,在几秒钟内转换所有内容会更容易。
这就是我的做法。它更具可读性且不易出错。转换为秒,然后进行比较。
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
bool earlierEqual(int h1, int m1, int s1, int h2, int m2, int s2)
{
int totalSeconds1 = getTotalSeconds(h1, m1, s1);
int totalSeconds2 = getTotalSeconds(h2, m2, s2);
if(totalSeconds1 <= totalSeconds2)
{
return true;
}
else
{
return false;
}
}
bool laterEqual(int h1, int m1, int s1, int h2, int m2, int s2)
{
int totalSeconds1 = getTotalSeconds(h1, m1, s1);
int totalSeconds2 = getTotalSeconds(h2, m2, s2);
if(totalSeconds1 >= totalSeconds2)
{
return true;
}
else
{
return false;
}
}
bool getTotalSeconds(int h1, int m1, int s1)
{
return h1 * 3600 + m1 * 60 + s1;
}
使用 std::tie
:
#include <tuple>
bool earlierEqual(int h1, int m1, int s1, int h2, int m2, int s2) {
return std::tie(h1, m1, s1) <= std::tie(h2, m2, s2);
}
bool laterEqual(int h1, int m1, int s1, int h2, int m2, int s2) {
return std::tie(h1, m1, s1) >= std::tie(h2, m2, s2);
}
只是一个建议:您可以在单个 32 位整数中表示小时 + 分钟+秒。 (小时为0-24-5位,秒
0-60:6位分钟0-60:6位)一旦你在两个整数中都有两个数字,你基本上把逻辑放在这个块中(你需要位掩码来提取小时、分钟、秒)
下面的伪代码:
bool compare(val1,val2) {
if(h1 < h2) return true;
if( h1 == h2 && m1 < m2 ) return true;
if( h1 == h2 && m1 == m2 && s1 <s2) return true;
return false ;
}
相关文章:
- 如何在C++中比较两个char数组
- 比较两个大小不等的映射c++
- 如何比较两个同名的预处理器宏?
- C++通过数字比较两个数字
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- 比较两个字符串后卡在无限循环中
- 比较两个节点坐标的最佳方法是什么?
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 比较两个公钥与OpenSSL API
- 如何比较两个函数的速度和性能
- 如何在两个列表中比较和获取非包含值
- 绘制一个对象,比较模具缓冲区的两个不同值
- 比较两个 constexpr 指针不是 constexpr?
- 比较两个 std::chrono::time_point 实例时出错
- 比较C++中两个BST的节点
- 比较两个没有一行共同点的大文件
- 比较两个整数在C++中与未知 int 类型的相等性
- >操作员在比较两个C++容器时会怎么做?
- 如何在 c++ 中比较两个文本文件
- if条件下两个字符串比较的优化代码