gpt4 book ai didi

c - 将当前时间更新一秒的程序

转载 作者:行者123 更新时间:2023-11-30 18:42:16 24 4
gpt4 key购买 nike

我正在学习 Kochan 的 C 语言编程。这是练习 9-5。程序将时间增加一秒。代码编译良好,但时间没有按预期更新。当我用

替换 timeUpdate 函数中的代码时
printf("Test");

它打印“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;
}

最佳答案

这是因为您在所有函数中按值传递结构并按值返回它。因此,在 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;
}

然后你必须将所有函数更改为接收指针,并且可以丢弃返回值。

关于c - 将当前时间更新一秒的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17432898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com