根据另一个变量的偶数/奇数状态更改变量?

发布于 2024-09-11 04:47:37 字数 208 浏览 0 评论 0原文

for($i=0;$i<$num;$i++) {
  if($i==even) $hilite="hilite";
  dothing($i,$hilite);
}

这基本上就是我想要实现的目标。 确定 $i 是否为偶数的最有效方法是什么? 我知道我可以检查 half == mod 2 是否...但这在计算上似乎有点过多?有没有更简单的方法?

for($i=0;$i<$num;$i++) {
  if($i==even) $hilite="hilite";
  dothing($i,$hilite);
}

This is basically what I want to accomplish.
What is the most efficient way to determine if $i is even?
I know I could check if half == mod 2 ... but that seems a little excessive on the calculations? Is there a simpler way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冰之心 2024-09-18 04:47:37

如果($i%2==0)

if ($i % 2 == 0)

惯饮孤独 2024-09-18 04:47:37

已经提到的 %2 语法是最常用的,对于其他程序员来说也是最易读的。如果您确实想避免计算的“开销”:

for($i = 0, $even = true; $i < $num; $i++, $even =! $even) {
  if($even) $hilite = "hilite";
  dothing($i,$hilite);
}

尽管赋值本身可能比“%2”(本质上只是位移)工作更多。

The already mentioned % 2 syntax is most used, and most readable for other programmers. If you really want to avoid an 'overhead' of calculations:

for($i = 0, $even = true; $i < $num; $i++, $even =! $even) {
  if($even) $hilite = "hilite";
  dothing($i,$hilite);
}

Although the assignment itself is probably more work then the '%2' (which is inherently just a bit-shift).

情深缘浅 2024-09-18 04:47:37

没有比 $i % 2 == 0 更简单的了。就这样。

It doesn't get any simpler than $i % 2 == 0. Period.

很糊涂小朋友 2024-09-18 04:47:37

将循环语句中的 i++ 更改为 i+=2,以便只检查 i 的偶数值?

Change the i++ in the loop statement to i+=2, so that you only examine even values of i?

妞丶爷亲个 2024-09-18 04:47:37

通常,如果设置了 LSB(最低有效位),则该数字为奇数。您可以使用 按位 AND 运算符检查该位的状态:

if($testvar & 1){
  // $testvar is odd
}else{
 // $testvar is even
}

在上面的代码中,更有效的方法是在每个循环中让 $i 增加 2(假设您可以忽略奇数值):

for($i=0;$i<$num;$i+=2){
  // $i will always be even!
}

Typically, a number is odd if it's LSB (Least Significant Bit) is set. You can check the state of this bit by using the bitwise AND operator:

if($testvar & 1){
  // $testvar is odd
}else{
 // $testvar is even
}

In your code above, a more efficient way would be to have $i increment by 2 in every loop (assuming you can ignore odd-values):

for($i=0;$i<$num;$i+=2){
  // $i will always be even!
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文