跳到主要内容

C++ 编程:计算两个时间段的差异

为了理解这个示例,你应该掌握以下 C++ 编程 相关主题:

示例:计算时间差的程序

// 计算两个时间段的时间差
// 时间段由用户输入

#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 << "输入开始时间。" << endl;
cout << "分别输入小时、分钟和秒:";
cin >> t1.hours >> t1.minutes >> t1.seconds;

cout << "输入结束时间。" << endl;
cout << "分别输入小时、分钟和秒:";
cin >> t2.hours >> t2.minutes >> t2.seconds;

computeTimeDifference(t1, t2, &difference);

cout << endl << "时间差: " << 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;
}

输出

分别输入小时、分钟和秒:11
33
52
输入结束时间。
分别输入小时、分钟和秒:8
12
15

时间差: 11:33:52 - 8:12:15 = 3:21:37

在这个程序中,用户被要求输入两个时间段,这两个时间段分别存储在结构体变量 t1t2 中。

然后,computeTimeDifference() 函数计算这两个时间段之间的差异,并且结果通过 main() 函数显示在屏幕上,而不是返回它(通过引用调用)。