栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

敲代码的第三天:创建时间类实现功能(c++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

敲代码的第三天:创建时间类实现功能(c++)

题目要求:再加两个功能:正数计时和倒数计时

 

#include

#include

using namespace std;

class Time {

public:

int hour;

int minute;

int sec;

Time() {

int hour=0;

minute = 0;

sec = 0;

}

Time(int h,int m, int s):hour(h),minute(m), sec(s)

{}

Time& operator++();

Time& operator--();

friend Time& operator+=(Time& a, Time& b);

friend Time& operator-=(Time& a, Time& b);

void Print();

};

Time& Time::operator++() {

sec++;

if (sec >= 60) {

sec -= 60;

minute++;

if(minute>=60){

minute-=60;

hour++;

}

}

return *this;

}

Time& Time::operator--() { 

sec--;

if (sec < 0) {

sec += 60;

minute--;

if(minute<0){

minute+=60;

hour--;

}

}

return *this;

}

Time& operator+=(Time& a, Time& b) {

int hour;

int minute;

int sec;

if (a.sec + b.sec >= 60) {

a.sec += b.sec;

a.sec -= 60;

a.minute++;

}

else {

a.sec += b.sec;

}

if (a.minute + b.minute >= 60) {

a.minute += b.minute;

a.minute -= 60;

hour++;

}

else {

a.minute += b.minute;

}

a.hour+=b.hour;

return a;

}

Time& operator-=(Time& a, Time& b) {

int hour;

int minute;

int sec;

int t1, t2, t;

t1 = a.hour*60*60+ a.minute * 60 + a.sec;

t2 = b.hour*60*60+b.minute * 60 + b.sec;

if (t1 >= t2) {

t = t1 - t2;

}

else {

t = t2 - t1;

}

a.hour = t/3600;

a.minute = t%/60;

a.sec = t % 60;这里有问题,研究清楚后改正

return a;

}

void Time::Print() {

cout << "当前时间是:";

cout <

}

int main() {

Time time1, time2, time3;

int a;

cout << "请输入小时:"<< endl;

cin  >>time1.hour;

cout << "请输入分钟:" << endl;

cin >> time1.minute;

cout << "请输入秒钟:" << endl;

cin >> time1.sec;

cout << "当前时间是:" << time1.hour<<"时:"<

cout << "--------------------------------" << endl;

cout << "请输入操作" << endl << "1.整数计时" << endl << "2.倒数计时" << endl << "3.时间相加" << endl << "4.时间相减" << endl;

cout << "--------------------------------" << endl;

while (scanf("%d", &a) != EOF) {

switch (a) {

case 1:

for (int i = 0; i < 8; i++) {

++time1;

Sleep(1000);

time1.Print();

}

break;

case 2:

for (int i = 0; i < 8; i++) {

--time1;

Sleep(1000);

time1.Print();

}

break;

case 3:

cout << "请输入需要相加的时间(时钟)" << endl;

cin >> time2.hour;

cout << "请输入需要相加的时间(分钟)" << endl;

cin >> time2.minute;

cout << "请输入需要相加的时间(秒钟)" << endl;

cin >> time2.sec;

time1 += time2;

time1.Print();

break;

case 4:

cout << "请输入需要相减的时间(时钟)" << endl;

cin >> time3.hour;

cout << "请输入需要相减的时间(分钟)" << endl;

cin >> time3.minute;

cout << "请输入需要相减的时间(秒钟)" << endl;

cin >> time3.sec;

time1 -= time3;

time1.Print();

break;

}

}

return 0;

}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/316089.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号