0

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

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

4 回答 4

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; 
于 2013-01-29T13:16:34.517 回答
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";
于 2013-01-29T13:18:14.390 回答
1

一种方法可能是(假设您想添加两次不是简单的小时分量)将是:

  1. 将第一次转换为总秒数(对每个组件使用适当的乘数,小时/分钟和秒。)
  2. 以同样的方式转换第二次
  3. 现在根据需要添加/减去 - 这将为您提供以秒为单位的新时间。
  4. 如果新时间小于 0,则添加一天的秒数,如果新时间大于一天的秒数,则减去
  5. 然后可以通过与您在步骤 1 中所做的相反的操作将结果以秒为单位的值分解为小时分钟和秒(提示您需要模运算符...)

编辑:哦,当人们(显然应该知道得更好)只是提供代码时,我为什么要费心尝试提供想法而不是代码... :(

于 2013-01-29T13:19:51.363 回答
0

正如 Ed Heal 所示,您可以在最低分辨率下进行计算(在您的示例中为秒)。

或从最不重要的值开始添加,并将进位添加到下一个值,如下所示:

#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;
}
于 2013-01-29T13:26:28.713 回答