我知道这可能是一个愚蠢的问题,但我有一些麻烦,我很惭愧,但我真的不知道,怎么做。我想以整数形式加上和减去两个“小时”。
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
// should be: 21:59:2
int rH, rM, rS;
int h1 = 12, m1 = 34, s1 = 56;
int h2 = 9, m2 = 24, s2 = 6;
if(h1 + h2 >= 24)
{
rH = abs(h2 + h1);
m1 += 60;
if(m1 + m2 >= 60)
{
rH = (m2 - m1);
}
}
else
{
rH = h1 + h2;
}
cout << rH << " " << rM << " " << rS << " " << "\n";
return 0;
}
尝试了以上但我不知道如何进一步做到这一点。我无法使用任何date-time
个对象。
修改
减法,我不知道错误在哪里,但计算错误:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
int rH, rM, rS;
int h1 = 12, m1 = 25, s1 = 29, h2 = 11, m2 = 12, s2 = 1;
int sum1, sum2, sum;
sum1 = (h1)*3600 + (m1)*60 + s1;
sum2 = (h2)*3600 + (m2)*60 + s2;
if(sum1 > sum2)
sum = sum1-sum2;
else
sum = sum2-sum1;
rS = sum %60;
sum = sum/60;
rM = sum % 60;
rH = sum/60;
std::cout << rH << " " << rM << " " << rS << " " << "\n";
return 0;
}
答案 0 :(得分:2)
为什么不
int t1 = ((h1 * 60) + m1) * 60 + s1;
int t2 = ((h2 * 60) + m2) * 60 + s2;
int tdiff = t1 - t2;
if (tdiff < 0) { tdiff += 24 * 60 * 60;
然后使用模运算和除法来获得小时等,例如
int tdiffs = tdiff % 60;
tdiff = tdiff / 60;
int tdiffm = tdiff % 60;
tdiff h = tdiff / 60;
答案 1 :(得分:1)
// addition
int rH=0, rM=0, rS=0;
rS = s1+s2;
if (rS>60)
{
rM++;
rS %= 60;
}
rM += m1+m2;
if (rM>60)
{
rH++;
rM %= 60;
}
rH += h1+h2;
if (rH>24)
{
// 1 day more, who cares
rH %= 24;
}
cout << rH << " " << rM << " " << rS << " " << "\n";
//减法
int rH = 0,rM = 0,rS = 0; int h1 = 12,m1 = 25,s1 = 29,h2 = 11,m2 = 12,s2 = 1;
rS = s1 - s2;
if (rS<0)
{
rM--;
rS += 60;
}
rM += m1 - m2;
if (rM<0)
{
rH--;
rM += 60;
}
rH += h1 - h2;
if (rH<0)
{
// Error occurred ...
}
cout << rH << " " << rM << " " << rS << " " << "\n";
答案 2 :(得分:1)
一种方法可能是(假设您想要添加两个次而不是简单的小时组件):
答案 3 :(得分:0)
您可以使用最低分辨率进行计算(在您的示例中为秒),如Ed Heal所示。
或以“Lest Significant Value”开头添加并将进位添加到下一个值:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
// should be: 21:59:2
int rH(0), rM(0), rS(0);
int h1 = 12, m1 = 34, s1 = 56;
int h2 = 9, m2 = 24, s2 = 6;
rS = s1 + s2;
while (rS >= 60)
{
rS -= 60;
rM++;
}
rM += m1 + m2;
while (rM >= 60)
{
rM -= 60;
rH++;
}
rH += h1 + h2;
while (rH >= 24)
{
rS -= 24;
}
cout << rH << " " << rM << " " << rS << " " << "\n";
return 0;
}