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

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

问题描述

我如何检查,如果给定的数字是奇数还是偶数用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\n", 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\n", 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是相同的(它们都使用了和L $ 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.

最后,模版本的保证按标准工作整数是正数,负数或零,不管有符号整数实施的再presentation的。按位和版本是没有的。是的,我知道补多少有些无处不在,所以这不是一个真正的问题。

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天全站免登陆