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 2014-05-08 22:20  zhuli19901106  阅读(156)  评论(0编辑  收藏  举报