简体   繁体   中英

How to get the number of variable b one less than a?

My numbers go in order from 0 to 3 But I need the variable b to be less by 1 and not go beyond.

Initially, the number is unknown, after receiving the number it is stored in only one variable, the number cannot be changed, but you need to get another number one less for the other variable.

I need to implement it like this.

1 A
0 B

2 A
1 B

3 A
2 B

0 A
3 B

1 A
0 B

What I have now

int i = 0, a = 0, b = 0;

for (;;)
{
    this_thread::sleep_for(chrono::milliseconds(500));


    i = (i + 1) % 4;

    a = i;

    b = i;

    cout << a << " A " << endl;

    cout << b << " B " << endl;

    cout << endl;

}

If I have understood correctly then just use

int b = i % 4;
int a = ++i % 4;

For example

#include <iostream>

int main() 
{
    for ( int i = 0; i < 10; )
    {
        const int divisor = 4;

        int b = i % divisor;
        int a = ++i % divisor;

        std::cout << a << " A " << '\n';
        std::cout << b << " B " << '\n';
        std::cout << '\n';
    }

    return 0;
}

The program output is

1 A 
0 B 

2 A 
1 B 

3 A 
2 B 

0 A 
3 B 

1 A 
0 B 

2 A 
1 B 

3 A 
2 B 

0 A 
3 B 

1 A 
0 B 

2 A 
1 B 

I like the idea of mch.

b=a; before a=i; and remove the b=i; should set b to the previous value.

int main() {
    int i = 0, a = 0, b = 0;

    for (;;)
    {
        this_thread::sleep_for(chrono::milliseconds(500));


        b = i % 4;
        i = (i + 1) % 4;

        a = i;

        cout << a << " A " << endl;

        cout << b << " B " << endl;

        cout << endl;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM