如何将两个'小时'加/减整数?

时间:2013-01-29 13:12:15

标签: c++ time

我知道这可能是一个愚蠢的问题,但我有一些麻烦,我很惭愧,但我真的不知道,怎么做。我想以整数形式加上和减去两个“小时”。

#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 个答案:

答案 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)

一种方法可能是(假设您想要添加两个而不是简单的小时组件):

  1. 将第一次转换为总秒数(对每个组件使用适当的乘数,小时/分钟和秒。)
  2. 以相同方式第二次转换
  3. 现在根据需要添加/减去 - 这将在几秒钟内为您提供新的时间。
  4. 如果新时间少于tan 0,则为其添加一天的秒数,如果新时间超过一天的秒数,则减去
  5. 然后,以秒为单位的结果值可以通过与步骤1中的操作相反的方式分解为小时分钟和秒钟(提示您需要模运算符...)
  6. 编辑:哦,为什么我在尝试提供想法而不是代码时,当民间(显然应该知道更好)只是提供代码时,我会费心.... :(

答案 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;
}