-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;
}
欢迎来到Stack Overflow。请尽快阅读[常见问题]。 IMNSHO,这三个功能并不是一个很好的设计。除了传递值与传递引用之外,具有'timeUpdate()'函数使结构保持非连贯状态(当小时从23变为24时)意味着在模块外部使用该函数并不安全。它应该全部在单个函数中处理,以确保当修改时间值时,结果总是与规则一致。 _ [... continue ...] _ –
_ [... continuation ...] _我相信这些规则是这样的:断言assert(now.seconds> = 0 && now.seconds <60 && now。 minutes> = 0 && now.minutes <60 && now.hours> = 0 && now.hours <24 && now.days> = 0);''不应该失败。 –
@JonathanLeffler其实[about](http://stackoverflow.com/about)页面可能比帮助中心好。 –