如何检查整数是偶数还是奇数? [英] How do I check if an integer is even or odd?

查看:25
本文介绍了如何检查整数是偶数还是奇数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中检查给定数字是偶数还是奇数?

How can I check if a given number is even or odd in C?

推荐答案

使用模(%)运算符判断除以2时是否有余数:

Use the modulo (%) operator to check if there's a remainder when dividing by 2:

if (x % 2) { /* x is odd */ }

一些人批评了我上面的回答,指出使用 x &1 是更快"或更高效".我不相信是这样的.

A few people have criticized my answer above stating that using x & 1 is "faster" or "more efficient". I do not believe this to be the case.

出于好奇,我创建了两个简单的测试用例程序:

Out of curiosity, I created two trivial test case programs:

/* modulo.c */
#include <stdio.h>

int main(void)
{
    int x;
    for (x = 0; x < 10; x++)
        if (x % 2)
            printf("%d is odd
", x);
    return 0;
}

/* and.c */
#include <stdio.h>

int main(void)
{
    int x;
    for (x = 0; x < 10; x++)
        if (x & 1)
            printf("%d is odd
", x);
    return 0;
}

然后我在我的一台机器上用 gcc 4.1.3 编译了 5 次:

I then compiled these with gcc 4.1.3 on one of my machines 5 different times:

  • 没有优化标志.
  • 带 -O
  • 使用 -Os
  • 使用 -O2
  • 使用 -O3

我检查了每次编译的汇编输出(使用 gcc -S),发现在每种情况下,and.c 和 modulo.c 的输出都是相同的(它们都使用了 andl $1, %eax 指令).我怀疑这是一个新"功能,我怀疑它可以追溯到古代版本.我也怀疑任何现代(过去 20 年制造的)非神秘编译器,无论是商业的还是开源的,都缺乏这种优化.我会在其他编译器上进行测试,但目前没有可用的.

I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment.

如果其他人愿意测试其他编译器和/或平台目标并得到不同的结果,我很想知道.

If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know.

最后,模版本保证无论整数是正数、负数还是零,无论实现对有符号整数的表示形式如何,模数版本都能正常工作.按位与版本不是.是的,我意识到二进制补码无处不在,所以这不是一个真正的问题.

Finally, the modulo version is guaranteed by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.

这篇关于如何检查整数是偶数还是奇数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆