2

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.

Aamir
  • 1,974
  • 1
  • 14
  • 18
Fidelity
  • 33
  • 4

1 Answers1

3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Aung
  • 191
  • 1
  • 4
  • Thank you, problem solved. When I looked at the values ​​of the debugger, I could not understand why it was adding characters to N. – Fidelity Nov 03 '22 at 09:54