Đề:
Viết chương trình đo thời gian
Khi nhấn phím Enter thì bắt đầu tính giờ. Nhấn phím Enter lần thứ 2 thì dừng tính giờ và hiển thị thời gian theo format: ##.## (số_giây.số_tick). Nếu thời gian dài quá 10s thì hiện chữ “EE.EEE” (như là 1 báo lỗi khi thời gian quá lâu)
Code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <time.h>
using namespace std;
class Clock {
public:
Clock();
~Clock();
void setClockStart();
void setClockStop();
void printresult();
private:
clock_t mStart, mStop;
};
Clock::~Clock()
{
}
Clock::Clock()
{
mStart = 0;
mStop = 0;
}
void Clock::setClockStart()
{
mStart = clock();
}
void Clock::setClockStop()
{
mStop = clock();
}
void Clock::printresult()
{
double duration;
duration = (mStop - mStart) / (double)CLOCKS_PER_SEC;
if (duration > 10)
cout << "\tEEEE";
else
cout << "\n time is : " << fixed << setprecision(2) << duration << "\n";
}
int main()
{
Clock test;
cout << "Enter any key to start" << endl;
_getch();
test.setClockStart();
cout << "Enter any key to stop" << endl;
_getch();
test.setClockStop();
test.printresult();
cout << endl << "Press any key to continue" << endl;
_getch();
}
Mình đã thử xóa if…else ở phần void Clock::printresult() và thêm vào while ở dưới hàm main, nhưng tất cả ý tưởng đều bị phá sản. Chương trình vẫn k tự ngừng chạy!
Cao nhân nào giúp mình với!