C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ 计算两个时间段差值的程序

计算两个时间段差值的C++程序

在本例中,我们将计算用户提供的两个时间段之间的差异。
要理解此示例,您应该了解以下C++ 编程 主题:
C++ 结构 C++ 结构和函数 C++ 结构指针

示例: 程序到时差

// Computes time difference of two time period
// Time periods are entered by the user
#include <iostream>
using namespace std;
struct TIME
{
  int seconds;
  int minutes;
  int hours;
};
void computeTimeDifference(struct TIME, struct TIME, struct TIME *);
int main()
{
    struct TIME t1, t2, difference;
    cout << "Enter start time." << endl;
    cout << "Enter hours, minutes and seconds respectively: ";
    cin >> t1.hours >> t1.minutes >> t1.seconds;
    cout << "Enter stop time." << endl;
    cout << "Enter hours, minutes and seconds respectively: ";
    cin >> t2.hours >> t2.minutes >> t2.seconds;
    computeTimeDifference(t1, t2, &difference);
    cout << endl << "TIME DIFFERENCE: " << t1.hours << ":" << t1.minutes << ":" << t1.seconds;
    cout << "-" << t2.hours << ":" << t2.minutes << ":" << t2.seconds;
    cout << " = " << difference.hours << ":" << difference.minutes << ":" << difference.seconds;
    return 0;
}
void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME *difference){
    
    if(t2.seconds > t1.seconds)
    {
       --t1.minutes;
        t1.seconds += 60;
    }
    difference->seconds = t1.seconds-t2.seconds;
    if(t2.minutes > t1.minutes)
    {
       --t1.hours;
        t1.minutes += 60;
    }
    difference->minutes = t1.minutes-t2.minutes;
    difference->hours = t1.hours-t2.hours;
}
输出
Enter hours, minutes and seconds respectively: 11
33
52
Enter stop time.
Enter hours, minutes and seconds respectively: 8
12
15
TIME DIFFERENCE: 11:33:52-8:12:15 = 3:21:37
在这个程序中,要求用户输入两个时间段,这两个时间段分别存储在结构变量 t1t2中。
然后, computeTimeDifference() 函数计算时间段之间的差异,结果从 main() 函数显示在屏幕上而不返回它(调用参考)。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4