2013-07-02 15 views
-1

我正在通過C中的Kochan編程工作。這是練習9-5。 程序將時間遞增1秒。代碼編譯正常,但時間不會按預期更新。當我與將當前時間更新一秒的程序

printf("Test"); 

替換timeUpdate函數的代碼它打印「測試」,所以它似乎並不像有與調用該函數的問題。然而,當我與

now.seconds = 2; 

什麼替換代碼,秒未更新爲2,請幫我調試我的代碼。如果我犯了很明顯的錯誤,我很抱歉。不幸的是,我是一個非常新鮮的初學者。

#include <stdio.h> 

struct dateAndTime 
{ 
    int days; 
     int hours; 
    int minutes; 
    int seconds; 
}; 

// Updates the time by one second 
struct dateAndTime timeUpdate(struct dateAndTime now) 
{ 
    now.seconds++; 
    if (now.seconds == 60) // One minute 
    { 
     now.seconds = 0; 
     now.minutes++; 
     if (now.minutes == 60) // One hour 
     { 
      now.minutes = 0; 
      now.hours++; 
     } 
    } 


    return now; 
} 


// Increments days by one when hours reaches 24 
struct dateAndTime dateUpdate(struct dateAndTime now) 
{ 
    now.days++; 
    now.hours = 0; 
    return now; 
} 

// Calls timeUpdate to increment time by one second 
struct dateAndTime clockKeeper(struct dateAndTime now) 
{ 
    timeUpdate(now); 

    // If hours reaches 24, increments dys by one 
    if (now.hours == 24) 
    { 
     dateUpdate(now); 
    } 

    return now; 
} 

int main(void) 
{ 
    struct dateAndTime clockKeeper(struct dateAndTime now); 
    struct dateAndTime present, future; 

    // Prompts and accepts user input 
    printf("Enter a time (dd:hh:mm:ss): "); 
    scanf("%i:%i:%i:%i", &present.days, &present.hours, 
     &present.minutes, &present.seconds); 

    future = clockKeeper(present); 

    // Prints updated time 
    printf("The updated time is: %.2i:%.2i:%.2i:%.2i\n", future.days, future.hours, 
     future.minutes, future.seconds); 

    return 0; 
} 
+0

歡迎來到Stack Overflow。請儘快閱讀[常見問題]。 IMNSHO,這三個功能並不是一個很好的設計。除了傳遞值與傳遞引用之外,具有'timeUpdate()'函數使結構保持非連貫狀態(當小時從23變爲24時)意味着在模塊外部使用該函數並不安全。它應該全部在單個函數中處理,以確保當修改時間值時,結果總是與規則一致。 _ [... continue ...] _ –

+0

_ [... continuation ...] _我相信這些規則是這樣的:斷言assert(now.seconds> = 0 && now.seconds <60 && now。 minutes> = 0 && now.minutes <60 && now.hours> = 0 && now.hours <24 && now.days> = 0);''不應該失敗。 –

+0

@JonathanLeffler其實[about](http://stackoverflow.com/about)頁面可能比幫助中心好。 –

回答

3

這是因爲按值傳遞結構和值所有函數返回它。因此在clockKeeper當您撥打timeUpdate時,您通過副本將被修改,但您實際上並沒有將副本本地更新爲clockKeeper

你做,你一定要記得給它分配一個回調到自身時,都會如:

struct dateAndTime clockKeeper(struct dateAndTime now) 
{ 
    now = timeUpdate(now); 
    // Note assignment back to `now` 

    // If hours reaches 24, increments dys by one 
    if (now.hours == 24) 
    { 
     now = dateUpdate(now); 
     // Note assignment back to `now` 
    } 

    return now; 
} 

或者,您可以參考通過結構,通過使用指針結構。

像這樣:

struct dateAndTime *dateUpdate(struct dateAndTime *now) 
{ 
    now->days++; 
    now->hours = 0; 
    return now; 
} 

然後,你必須改變所有函數接收指針,則可以放棄返回值。

相關問題