📜  将给定时间转换/规范化为标准形式的 C++ 程序

📅  最后修改于: 2022-05-13 01:55:38.200000             🧑  作者: Mango

将给定时间转换/规范化为标准形式的 C++ 程序

给定代表小时、分钟和秒的三个变量,任务是编写一个 C++ 程序,将给定的时间规范化/转换为标准形式,即HR:MIN:SEC格式。

例子:

方法:为了规范给定的时间,以下是使用该类的功能/步骤:

  • 定义了 3 个变量分别存储小时、分钟和秒的值。
int HR, MIN, SEC;
where HR represents hours,
      MIN represents minutes and
      SEC represents seconds
  • setTime()函数设置 HR、MIN 和 SEC 的值:
void setTime(int x, int y, int z)
{
    x = HR;
    y = MIN;
    z = SEC;
}
  • showTime()显示时间:
void showTime()
{
    cout << HR << ":" << MIN << ":" << SEC;
}
  • normalize()函数将结果时间转换为标准形式。通过根据标准时间格式将时间转换为标准化时间:
void normalize()
{
    MIN = MIN + SEC/60;
    SEC = SEC%60;
    HR  = HR + MIN/60;
    MIN = MIN%60;
}

插图:例如时间:5:125:130



  • 使时间正常化:
    • 首先,将 SEC 除以 60 并找到分钟并将其添加到 MIN,
    • 所以,125+(130/60) =125+2 = 127。
  • 然后取 SEC 的模数找到秒 130 % 60 = 10。
  • 现在,将 MIN 除以 60 找到小时数,并将其添加到 HR 中,5+(127/60) = 5+2= 7。
  • 最后取 MIN 的模数来求分钟数,127 % 60 = 7,所以,HR=7,MIN=7,SEC=10。
  • 所以结果是7:7:10

下面是上述方法的实现:

C++
// C++ program to normalize the given
// time into standard form
#include 
#include 
using namespace std;
 
// Time class
class Time {
private:
    // Instance variables
    int HR, MIN, SEC;
 
public:
    void setTime(int, int, int);
    void showTime();
    void normalize();
};
 
// Function that sets the given time
void Time::setTime(int h, int m, int s)
{
    HR = h;
    MIN = m;
    SEC = s;
}
 
// Function to show the given time
void Time::showTime()
{
    cout << endl
         << HR << ":"
         << MIN << ":" << SEC;
}
 
// Function to normalize the given
// time into standard form
void Time::normalize()
{
    // Convert the time into the
    // specific format
    MIN = MIN + SEC / 60;
    SEC = SEC % 60;
    HR = HR + MIN / 60;
    MIN = MIN % 60;
}
 
// Driver Code
int main()
{
    // Object of class Time
    Time t1;
 
    t1.setTime(5, 125, 130);
    t1.showTime();
 
    // Normalize the time
    t1.normalize();
    t1.showTime();
 
    return 0;
}


输出:

想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程