Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The while loop doesnt stop on a boolean condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading