按升序输出两个时间值

Output two time values in ascending order

本文关键字:两个 时间 升序 输出      更新时间:2023-10-16

在提示用户输入两个时间值后,我在按升序输出一个类的两个对象(t1和t2)时遇到一些问题。我知道bool和if结构的构造方式有一些错误。任何帮助都将不胜感激!

bool lessthan(Time t2) //For two Time objects t1 and t2, t1.lessthan(t2) returns true if t1 is less than, or comes before t2.
{
    if (hours < t2.hours)
    {
        return true;
    }
    if (minutes < t2.minutes)
    {
        return true;
    }
    if (seconds < t2.seconds)
    {
        return true;
    }
    return false;
}

bool greaterthan(Time t2)  //For two Time objects t1 and t2, t1.greaterthan(t2) returns true if t1 is greater than, or comes after t2.
{
    if (hours > t2.hours)
    {
        return true;
    }
    if (minutes > t2.minutes)
    {
        return true;
    }
    if (seconds > t2.seconds)
    {
        return true;
    }
    return false;
}

bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
    if (hours == t2.hours)
    {
        return true;
    }
    if (minutes == t2.minutes)
    {
        return true;
    }
    if (seconds == t2.seconds)
    {
        return true;
    }
    return false;
}

在主要功能中,我有以下代码:

 cout << "nTime values entered in ascending order: "<<endl;
        if (t1.lessthan(t2))
            t1.write();
        cout << endl;
            t2.write();
        cout << endl;

我认为相等的类应该是

bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
    if (hours != t2.hours)
    {
        return false;
    }
    if (minutes != t2.minutes)
    {
        return false;
    }
    if (seconds != t2.seconds)
    {
        return false;
    }
    return true;
}

在您的代码中,如果小时是相同的,与分钟和秒无关,那就足够了。在我的版本中,我颠倒了逻辑顺序。

对于比较函数,请尝试:

bool equalto(Time t2) //For two Time objects t1 and t2, t1.equalto(t2) returns true if t1 is equal to, or is the same time as t2.
{
    if (hours == t2.hours && minutes == t2.minutes && seconds == t2.seconds)
    {
        return true;
    }
    return false;
}
bool lessthan(Time t2) //For two Time objects t1 and t2, t1.lessthan(t2) returns true if t1 is less than, or comes before t2.
{
    if (hours > t2.hours)
    {
        return false;
    }
    if (minutes > t2.minutes)
    {
        return false;
    }
    if (seconds > t2.seconds)
    {
        return false;
    }
    return true;
}

然后根据的其他两个函数实现greaterthan()

greaterthan(Time t2)
{
    return (!(equalto(t2) || lessthan(t2));
}

此外,如果你想按升序输出时间,你需要做这样的事情:

cout << "nTime values entered in ascending order: "<<endl;
if (t1.lessthan(t2))
{
    t1.write();
    cout << endl;
    t2.write();
    cout << endl;
}
else
{
    t2.write();
    cout << endl;
    t1.write();
    cout << endl;
}

对于当前代码,最后3行将始终执行,因为它们与if语句无关。你需要括号。