所以我试图让时间功能倒计时。它基于我在这里看到的东西。变量由不同的函数给出。一旦时间用完,变量finish就会变为1并且它会离开函数。 这个功能有时有效,有时它不起作用,例如,如果我给它一个11秒的输入它工作正常,但如果我给它1分钟它不起作用。有人能告诉我代码有什么问题。
if (time1 == 0 && time2 == 0 && time3 == 0 && time4 == 0)
//if all the time is 0 finish the sequence
finish = 1;
if (time1 != 0) //Checking to see if the first digit is NOT at 0
time1 = time1 - 1; // subtract time 1 by 1
else {
time2 = time2 - 1; //When time1 is 0
time1 = 9;
} //Time1 going back to it's original value
if (time2 == 0 && time1 == 0) { //if time1 and time2 are 0s
if (time3 != 0) { //The minute value (time3)
time2 = 5; //60 SECONDS
time3 = time3 - 1;
time1 = 9;
}
} //Put time 1 to its original value
if (time2 <= 0 && time1 <= 0 && time3 <= 0) {
if (time4 != 0) { //The minute value (time3)
time2 = 5; //60 SECONDS
time3 = 9;
time4 = time4 - 1;
time1 = 9;
}
} //Put time 1 to its original value
Time4 = 3,Time3 = 2,Time2 = 1,Time1 = 0.这意味着时间是32:10 min
答案 0 :(得分:3)
您不能只检查非零,您需要检查给定时间是否为正,否则您将受到负值的计数,并且计数器可能会溢出。
if (time1 > 0)
time1 -= 1;
if (time3 > 0)
time3 -= 1;
另一个想法是,你用分钟和秒的每个数字倒计时,为什么不只是使用秒,将你的时间转换为秒。例如,倒计时1:23:
int minutes = 1;
int seconds = 23;
int timer = minutes * 60 + seconds;
// in your timer function
if (seconds == 0) {
finish = 1;
} else if (seconds > 0) {
seconds -= 1;
} else {
// error
}
这样它也是可扩展的,如果你想处理几个小时,只需将hours * 3600
添加到seconds
,你就可以轻松地处理几天甚至几个月。在你的方法中,添加那些会导致太多情况,它们几乎不可能正确处理。
答案 1 :(得分:2)
问题在于,在将数字更改为非零后,您将比较为零。
假设1:00编码为
time1 = 0
time2 = 0
time3 = 1
你可以遵循自己的逻辑:
if (time1 != 0) // Nope
time1 = time1 - 1;
else { // Yes
time2 = time2 - 1;
time1 = 9;
}
现在你有了
time1 == 9
time2 == 0
time3 == 1
if (time2 == 0 && time1 == 0) { // Nope, time1 is 9
if (time3 != 0) {
time2 = 5;
time3 = time3 - 1;
time1 = 9;
}
}
你还有
time1 == 9
time2 == 0
time3 == 1
最后
if (time2 <= 0 && time1 <= 0 && time3 <= 0) { // Nope
if (time4 != 0) {
time2 = 5;
time3 = 9;
time4 = time4 - 1;
time1 = 9;
}
}
所以你最终得到了
time1 == 9
time2 == 0
time3 == 1
即1:09。
您想要更改时间 k 的唯一时间是 k-1 时间“越过”零时。
这可以通过一组条件来完成:
if (time1 > 0 || time2 > 0 || time3 > 0 || time4 > 0)
{
time1 -= 1;
if (time1 < 0)
{
time1 = 9;
time2 -= 1;
if (time2 < 0)
{
time2 = 5;
time3 -= 1;
if (time3 < 0)
{
// ...
}
}
}
}