随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(158)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示