c - 优化 C 中的 while 循环?

标签 c while-loop

有没有更好的方法在 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/

相关文章:

python - 在 pygame 中来回移动 Sprite

javascript - 在 while 循环中增加一个 object.position.set

C系统函数导致错误 'sh: Syntax error: "("unexpected '

使用 void 指针在结构之间创建链接

c - 我是否需要为未明确定义的指针分配内存?

php - 更新已设置的 php 变量

mysql - 如何在Mysql过程中使用两个while语法

c - 如何在Ubuntu上编译modsecurity?

c - 在 C 中共享子项和父项之间的链表

linux - 我在 unix 中 at 作业的输出中不断收到 'while syntax' 错误,我不知道为什么