2401_86607194 2024-11-27 12:38 采纳率: 62.5%
浏览 15

用C语言写时间间隔(多实例测试)问题

img

运用函数方式解决时间间隔(多实例测试)问题 只用C语言写 以及主函数与子函数直接的关系 子函数如何返回数值

  • 写回答

1条回答 默认 最新

  • 想要AC的dly 2024-11-29 14:53
    关注
    #include <iostream>
    #include <iomanip> 
    
    using namespace std;
    
    int HmsToS(int h, int m, int s) {
        return h * 3600 + m * 60 + s;
    }
    
    void PrintTime(int s) {
        int hours = s / 3600;
        s %= 3600;
        int minutes = s / 60;
        int seconds = s % 60;
    
        cout << setw(2) << setfill('0') << hours << ":"
             << setw(2) << setfill('0') << minutes << ":"
             << setw(2) << setfill('0') << seconds << endl;
    }
    
    int main() {
        string time1, time2;
        int h1, m1, s1, h2, m2, s2;
    
        while (cin >> time1 >> time2) {
            // 解析时间点1
            h1 = stoi(time1.substr(0, 2));
            m1 = stoi(time1.substr(3, 2));
            s1 = stoi(time1.substr(6, 2));
    
            // 解析时间点2
            h2 = stoi(time2.substr(0, 2));
            m2 = stoi(time2.substr(3, 2));
            s2 = stoi(time2.substr(6, 2));
    
            // 计算时间差
            int totalSeconds1 = HmsToS(h1, m1, s1);
            int totalSeconds2 = HmsToS(h2, m2, s2);
            int diffSeconds = totalSeconds2 - totalSeconds1;
            PrintTime(diffSeconds);
        }
        return 0;
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月27日