2013-07-02 14 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; 
} 

然后,你必须改变所有函数接收指针,则可以放弃返回值。

相关问题