有没有更好的方法在 C 中编写以下 while 循环
while (x > 0 && x <= 16)
// do this
while (x > 16 && x <= 32)
// do that
while (x > 32 && x <= 48)
//do this
while (x > 48 && x <= 64)
//do that
while ( x > 64 && x <= 80)
//do this
....等等
我必须达到一个荒谬的高数字,我想知道是否有更好的方法来做到这一点?我是编码新手,所以任何建议都会有所帮助。
最佳答案
根据您的评论,您正在执行两个操作之一,具体取决于 x 属于 16 的倍数的范围。请注意:
x | (x-1)/16 | ((x-1)/16)%2
----+----------+--------------
1 | 0 | 0
15 | 0 | 0
16 | 0 | 0
17 | 1 | 1
31 | 1 | 1
32 | 1 | 1
33 | 2 | 0
50 | 3 | 1
68 | 4 | 0
... | ... | ...
因此您可以使用 ((x-1)/16)%2
来确定要执行的操作:
while (x < ridiculous_high_number) {
if (((x-1)/16) % 2 == 0) {
//do this
}
else {
//do that
}
}
关于c - 优化 C 中的 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21806593/