如何实现循环计数器?

时间:2022-10-31 19:15:50

I want to make a circular counter in C programming. First variable can store value from 0-3. Second variable asks the value from user (from 0-3). Third variable asks user to move either left or right

我想在C编程中制作一个循环计数器。第一个变量可以存储0-3的值。第二个变量询问用户的值(从0到3)。第三个变量要求用户向左或向右移动

If third variable is left the second variable should move left:

如果剩下第三个变量,则第二个变量应向左移动:

3->2
2->1
1->0
0->3

Similarly if third variable is right the second variable should move right:

同样,如果第三个变量是正确的,则第二个变量应向右移动

0->1
1->2
2->3
3->0

2 个解决方案

#1


2  

#include <stdio.h>

int main(void)
{
    int max = 3, num, i;

    num = 0;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (num + 1) % (max + 1);
    }
    puts("--");
    num = max;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (max - -num) % (max + 1);
    }
    return 0;
}

Output:

输出:

0
1
2
3
0
1
2
3
0
1
--
3
2
1
0
3
2
1
0
3
2

#2


0  

If you wrap at a power of two, then this technique will work.

如果你以2的幂包裹,那么这种技术将起作用。

#include <stdio.h>

typedef struct
{
    unsigned int x : 2;    /* Holds up to 4 values */

} SmallInt;


int main()
{
    SmallInt up   = {0};
    SmallInt down = {0};

    for (int z = 0; z < 10; z++)
    {
        printf("%d %d\n", up.x, down.x);

        up.x++;
        down.x--;
    }

    return 0;
}

#1


2  

#include <stdio.h>

int main(void)
{
    int max = 3, num, i;

    num = 0;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (num + 1) % (max + 1);
    }
    puts("--");
    num = max;
    for (i = 0; i < 10; i++) {
        printf("%d\n", num);
        num = (max - -num) % (max + 1);
    }
    return 0;
}

Output:

输出:

0
1
2
3
0
1
2
3
0
1
--
3
2
1
0
3
2
1
0
3
2

#2


0  

If you wrap at a power of two, then this technique will work.

如果你以2的幂包裹,那么这种技术将起作用。

#include <stdio.h>

typedef struct
{
    unsigned int x : 2;    /* Holds up to 4 values */

} SmallInt;


int main()
{
    SmallInt up   = {0};
    SmallInt down = {0};

    for (int z = 0; z < 10; z++)
    {
        printf("%d %d\n", up.x, down.x);

        up.x++;
        down.x--;
    }

    return 0;
}