计算军事时间c ++的差异

时间:2017-10-24 17:22:50

标签: c++

我已经把它的大部分内容搞砸了如何让程序在从PM到AM时吐出正确的答案。例如2300到1000.这是我到目前为止:

void timeTraveled(int startTime, int endTime) {
    int min1 = (startTime / 100) * 60 + (startTime % 100);
    int min2 = (endTime / 100) * 60 + (endTime % 100);
    int ans1 = min2 - min1;
    if (ans1 > 0) {
        cout << "You have traveled " << ans1 << " minutes into the future!" << endl;
    }
    else {
        int ans2 = abs(ans1) + 24;
        cout << "You have traveled " << ans2 << " minutes into the future!" << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

这个问题有很多正确的答案,它更多的是直接得到数学,而不是编程。这可能是一种更直接的推理方式:

void timeTraveled(int startTime, int endTime) {
    if (endTime < startTime) { // Assume next day if endTime is before start time
        endTime += 2400;
    }

    int min1 = (startTime / 100) * 60 + (startTime % 100);
    int min2 = (endTime / 100) * 60 + (endTime % 100);
    int ans1 = min2 - min1;
    cout << "You have traveled " << ans1  << " minutes into the future!" << endl;
}

你的方式很接近,它只有几个简单的错误:

void timeTraveled(int startTime, int endTime) {
    int min1 = (startTime / 100) * 60 + (startTime % 100);
    int min2 = (endTime / 100) * 60 + (endTime % 100);
    int ans1 = min2 - min1;
    if (ans1 > 0) {
        cout << "You have traveled " << ans1 << " minutes into the future!" << endl;
    }
    else { // Assume next day
        int ans2 = ans1 + (24 * 60); // Add 24 Hours worth of minutes
        cout << "You have traveled " << ans2 << " minutes into the future!" << endl;
    }
}