在C ++中计算两次之间的差

时间:2018-10-29 00:03:51

标签: c++

我想计算两个给定时间之间的差异(格式为“ HH:MM xm”,其中“ xm”为“ am”或“ pm”)

到目前为止,我尝试过的是:

#include <iostream>
using namespace std;
// Function Declarations
int ComputeDifference(int startHr, int startMin, int endMin, int endHr, bool isAM1, bool isAM2);// 6 parameters
// Main Function
int main()
{
    //Declaring Variables
    int startHour, endHour, startMinute, endMinute, Minutes, Hours;
    bool isAM1 = false, isAM2 = false;
    char AM1, PM1, AM2, PM2, colon, answer;
    //Function Calls and a loop
    do
    {
        cout << "Enter start time, in the format 'HH:MM xm' where 'xm' is niether 'am' or 'pm': " << endl;
        cin >> startHour >> colon >> startMinute >> AM1 >> PM1;
        cout << "Enter future time, in the format 'HH:MM xm' where 'xm' is niether 'am' or 'pm': " << endl;
        cin >> endHour >> colon >> endMinute >> AM2 >> PM2;
        if ((AM1 == 'a') || (AM1 == 'A'))
            isAM1 = true;
        if ((AM2 == 'a') || (AM2 == 'A'))
            isAM2 = true;
        Minutes = ComputeDifference(startHour, startMinute, endMinute, endHour, isAM1, isAM2) % 60;
        Hours = ComputeDifference(startHour, startMinute, endMinute, endHour, isAM1, isAM2) / 60;
        cout << "There are " << ((Minutes) + (Hours * 60)) << " minutes (" << Hours << " hours and " << Minutes << " minutes) between " << startHour << colon << startMinute << AM1 << PM1 << " and " << endHour << colon << endMinute << AM2 << PM2 << "."<< endl;
        cout << "Do you want to run another session? (y/n): ";
        cin >> answer;
        if (answer == 'y' || answer == 'Y')
        {
            isAM1 = false;
            isAM2 = false;
        }
    } while ((answer == 'y' || answer == 'Y'));
    return 0;
}

//功能定义

int ComputeDifference(int startHr, int startMin, int endMin, int endHr, bool isAM1, bool isAM2)
{
    int difference = 0;
    if ((isAM1 == true) && (isAM2 == false))
    {
        if (startHr == 12)
        {
            startHr = 0;
        }
        difference = (((endHr - startHr)*(60)) - ((startMin)-(endMin)));
        return difference;
    }
}

但是,为了计算下午3:45和上午12:56之间的差异,它给了我以下输出:“下午3:45和上午12:56之间有1分钟(0小时零1分钟)。”

enter image description here

我没弄错我的地方。我是C ++的新手,所以如果我遗漏任何明显的内容,我深表歉意。

1 个答案:

答案 0 :(得分:0)

int ComputeDifference(int startHr, int startMin, int endMin, int endHr, bool isAM1, bool isAM2) {
    if (startHr == 12) isAM1 = !isAM1;
    if (endHr == 12) isAM2 = !isAM2;

    int start_time = startHr * 60 + startMin + (isAM1 ? 0 : 12 * 60); 
    int end_time = endHr * 60 + endMin + (isAM2 ? 0 : 12 * 60);
    int difference = end_time - start_time;
    return difference > 0 ? difference : 24 * 60 - difference;
}

Test