2014-05-08 22:09
原题:
Implement a class to create timer object in OOP
题目:用OOP思想设计一个计时器类。
解法:我根据自己的思路,用clock()函数为工具,提供启动、停止、显示时长、重置四个方法。
代码:
1 // http://www.careercup.com/question?id=5692127791022080 2 #include <ctime> 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 class Timer { 8 public: 9 Timer(): begin(0), end(0) {}; 10 11 clock_t ticks() { 12 if (begin == 0) { 13 return end; 14 } else { 15 end = clock(); 16 return end - begin; 17 } 18 }; 19 20 double seconds() { 21 return 1.0 * ticks() / CLOCKS_PER_SEC; 22 }; 23 24 void start() { 25 begin = clock(); 26 }; 27 28 void stop() { 29 if (begin > 0) { 30 end = clock(); 31 end -= begin; 32 begin = 0; 33 } 34 }; 35 36 void reset() { 37 begin = end = 0; 38 }; 39 private: 40 clock_t begin, end; 41 }; 42 43 int main() 44 { 45 Timer timer; 46 string cmd; 47 48 while (cin >> cmd) { 49 if (cmd == "start") { 50 timer.start(); 51 } else if (cmd == "stop") { 52 timer.stop(); 53 } else if (cmd == "time") { 54 printf("%.2f seconds.\n", timer.seconds()); 55 } else if (cmd == "reset") { 56 timer.reset(); 57 } 58 } 59 60 return 0; 61 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)