此範例為讓一個隨著Sleep函數,持續在執行的程式
並利用了struct 和 取址運算子去讓 time struct 的秒數一直增加
#include <iostream>
#include <windows.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct time
{
int hour;
int minute;
int second;
};
// 透過函數可以給予一些限制,防止賦予值時造成錯誤,struct 是沒辦法做到的
time time_init(int h, int m, int s)
{
time t;
if(h > 23)
t.hour = 23;
else if ( h < 0)
t.hour = 0;
else
t.hour = h;
if(m > 59)
t.minute = 59;
else if ( m < 0)
t.minute = 0;
else
t.minute = m;
if(s > 59)
t.second = 59;
else if ( s < 0)
t.second = 0;
else
t.second = s;
return t;
}
void next_second(time & t)
{
t.second ++;
if(t.second >= 60)
{
t.minute++;
t.second = 0;
}
if(t.minute >= 60)
{
t.hour++;
t.minute = 0;
}
if(t.hour >= 24)
t.hour = 0;
}
void S0901(void) {
// time midnight;
// midnight.hour = 12;
// midnight.minute = 0;
// midnight.second = 0 ;
// time t1 = {11,34,23};
// cout << "中原標準時間為:"
// << midnight.hour << ":0"
// << midnight.minute << ":0"
// << midnight.second << " AM"
// << endl;
time t1 = {11,34,23};
t1 = time_init(23,58,59);
while(1)
{
next_second(t1);
cout << "中原標準時間為:"
<< t1.hour << ":"
<< t1.minute << ":"
<< t1.second
<< endl;
Sleep(100);
}
}
顯示結果如下:
沒有留言:
張貼留言