所以我正在尝试制作一个倒计时的时间函数。这是基于我在这里看到的东西。变量由不同的函数给出。一旦时间用完,变量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分钟
您不能只针对非零进行检查,您需要检查给定时间是否为正,否则您将使用负值进行计数,计数器可能会溢出。
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: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)
{
// ...
}
}
}
}