在C中优化while循环?

用户名

有没有更好的办法在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
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章