我正在完成 Kochan 的 C 编程。这是练习 9-5。程序将时间增加一秒。代码编译正常,但时间没有按预期更新。当我将 timeUpdate 函数中的代码替换为
printf("Test");
它打印“测试”,因此调用该函数似乎没有问题。但是,当我将代码替换为
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;
}