gpt4 book ai didi

c++ - 如何将两个 'hours' 作为整数相加/相减?

转载 作者:行者123 更新时间:2023-11-27 23:19:09 27 4
gpt4 key购买 nike

我知道这可能是个愚蠢的问题,但我遇到了一些麻烦,我很惭愧,但我真的不知道如何做到。我想加减两个以整数形式给出的“小时”。

#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;
}

最佳答案

为什么不

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;

关于c++ - 如何将两个 'hours' 作为整数相加/相减?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com