在提示用户输入两个时间值后,我有一些问题以升序输出类(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;
答案 0 :(得分:0)
我认为同等级应该是
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;
}
在你的代码中,如果小时数相同,就足够了,与分钟和秒无关。在我的版本中,我颠倒了逻辑顺序。
答案 1 :(得分:0)
对于比较功能,请尝试:
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语句无关。你需要括号。