c - 返回 1 或 0 的函数

标签 c algorithm

<分区>

我的提示如下:

编写一个名为 alternator 的函数的定义,该函数不接收任何参数并在第一次调用时返回 1,在下次调用时返回 0,然后是 1、0 等等,在连续调用时在 1/0 之间交替.

我的尝试是:

int alternator(void) {

    static int x = 0;

    if(x == 0) {
        return 1;
    }

    else if (x % 2 == 0) {
        return 1;
        x++;
    }
    else {
        return 0;
        x++;
    }

}

我哪里出错了?

最佳答案

我更喜欢 xor 因为如果你可以调用 alternator 的次数没有上限:

int alternator(void) {
    static int x = 0;  // set to 1 if you want 0 as first value...
    return x ^= 1;
}

演示:

int main(int argc, char *argv[]) {
    for(int i=0; i<10; i++){
        printf("%d   %d\n", i, alternator());
    }

}

打印:

0   1
1   0
2   1
3   0
4   1
5   0
6   1
7   0
8   1
9   0

正如评论中指出的,您还可以:

int alternator(void) {
    static int x = 0;
    return x = !x;
}

关于c - 返回 1 或 0 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468675/

相关文章:

c - Islower功能故障

c - 如何单独使用指针遍历字符串数组

jquery - 在 Jquery 中计算特定日期将落在哪一天?

algorithm - 数字金字塔算法 : Numbers 1-15 in a pyramid where each number is the difference of the subjacent numbers

algorithm - 什么是最优的 "most general unifier"算法?

c - 在c中查找特定文件类型并保存

android - NDK 使用什么标志来发布 lib

c - C 中使用 pthread 的递归函数

algorithm - key 算法对 Keygen 免疫?

php - 相当于 glob() ,它可以使用数组而不是文件系统