我的目标是编写一个程序来执行以下操作: 当用户在将来输入时间点时,它应以格式(hh:mm:ss)显示该时刻之前的时间, 如果用户要求时间,则应以格式(hh:mm:ss)返回当前时间。如何使用系统时间来实现目标? 我目前的状况:
#include <iostream>
#include<conio.h>
using namespace std;
class Time{
int hour, minute, second;
public:
void SetTime(int hour1=0, int minute1=0, int second1=0){
hour = hour1;
minute=minute1;
second=second1;
cout<<"set time working";
}
void display(){
cout<<"hour | minute | second"<<endl;
cout<<hour<<" "<<minute<<" "<<second;
}
};
int main(){
Time time;
//char om;
int hour1, minute1,second1;
cout<<"enter the hour,minute,second: ";
cin>>hour1;
cin>>minute1;
cin>>second1;
time.SetTime(hour1,minute1,second1);
cout<<"\n The current time?";
time.display();
return 0;
}
答案 0 :(得分:1)
我建议你稍微作弊。在开始时,在用户输入时间之前或之后,您将获得系统时钟值。然后你等待用户要求时间。当他询问时,再次获得系统时钟值,从中减去前一个值 - 这将给你通过的时间量。将此金额添加到用户输入的时间,并显示结果。
答案 1 :(得分:0)
您必须使用C时间功能来获取计算机时钟的时间。
基本思路如下:
什么时候显示更新的当前时间:
要做到这一点,由于C“时间”功能如何工作,我将在程序中存储时间变量,以秒为单位,因此我必须在一个存储秒的单个变量中转换小时,分钟和秒。 / p>
这是功能:
#include <iostream>
#include <conio.h>
#include <time.h>
using namespace std;
class Time {
private:
time_t userTime;
time_t computerTime;
public:
void SetTime(int hour1 = 0, int minute1 = 0, int second1 = 0)
{
userTime = hour1 * 60 * 60 + minute1 * 60 + second1; // Convert input time in seconds.
time(&computerTime); // Get computer's current time.
cout<<"set time working";
}
void display()
{
time_t currentComputerTime;
time(¤tComputerTime); // Get computer's updated current time.
time_t currentUserTime = userTime + (currentComputerTime - computerTime); // Calculate current user's time in seconds.
// Convert time_t variable in hours, minutes and seconds.
int hour = currentUserTime / (60 * 60);
int minute = (currentUserTime / 60) % 60;
int second = currentUserTime % 60;
cout<<"hour | minute | second"<<endl;
cout<<hour<<" "<<minute<<" "<<second;
}
};
int main()
{
Time time;
//char om;
int hour1, minute1,second1;
cout<<"enter the hour,minute,second: ";
cin>>hour1;
cin>>minute1;
cin>>second1;
time.SetTime(hour1,minute1,second1);
char pcz[200];
cout<<"\n The current time?";
cin >> pcz;
time.display();
return 0;
}