2013-12-10 23 views
0

在提示用戶輸入兩個時間值後,我有一些問題以升序輸出一個類(t1和t2)的兩個對象。我知道布爾和構造是如何構造的,有一些錯誤。任何幫助,將不勝感激!按升序輸出兩個時間值

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

我覺得等於級應該是

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; 
} 

在你的代碼就足夠了,如果時間是它們是相同的,與分鐘和秒無關。在我的版本中,我顛倒了邏輯順序。

+0

非常感謝您的意見!但它仍然無法正常運行。另外,如果我輸入以相同數字開頭的兩個值(例如08:35:45,然後是05:32:56),則只打印後者。 – user3085117

+0

您是否在您的問題中顯示完整的輸出代碼?因爲't1.write()'只會在t1較小時調用,無論如何都會調用't2.write()'。 –

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; 
} 

隨着你目前的鱈魚e,最後3行將始終執行,因爲它們與if語句無關。你需要括號。