Home > Net >  The while loop doesnt stop on a boolean condition
The while loop doesnt stop on a boolean condition

Time:11-03

I wrote a simple code to solve an artificial problem. I want the program to exit the loop body after N =< 3, but the iterations continue after the condition isn't met. Where did i go wrong?

int main(){

    uint8_t N = 0;
    int power = 1;
    std::cin >> N;

    while (N >= 4){
        power *= 3;
        N -= 3;
    }
        
    power *= N;
    std::cout << power;
    
    return 0;
}
gcc 12.2.0. Flags -Wall -O2

I tried to use a loop for (N; N >= 4; N -=3), but result didn't change.

CodePudding user response:

uint8_t is char type.

In stdint.h,

typedef unsigned char      uint8_t;

'4' will be resulted in integer 52 due to implicit casting.

You may just use int type if you are accepting number.

  • Related