Question

decimal 45 is 101101 in binary, when I have to explain the code I get to 1011001, but program outputs the right answer. Where does this 0 go 10110 0 1 after 2 mod 2 = 0?

I followed the steps in program if I type 45 as decimal number:

  • 45 mod 2 = 1, x = "1"
  • " " + "1" = "1"
  • 45 div 2 = 22
  • 22 mod 2 = 1, x = "0"
  • "1" + "0" = "10"
  • 22 div 2 = 11
  • 11 mod 2 = 1, x = "1"
  • "10" + "1" = "101"
  • 11 div 2 = 5
  • 5 mod 2 = 1, x = "1"
  • "101" + "1" = "1011"
  • 5 div 2 = 4
  • 4 mod 2 = 0, x = "0"
  • "1011" + "0" = "10110"
  • 4 div 2 = 2
  • 2 mod 2 = 0, x = "0"
  • "10110" + "0" = "101100"
  • 2 div 2 = 1
  • 1 mod 2 = 1, x = "1"
  • "101100" + "1" = "1011001"
  • 1 div 2 = 0
  • program ends

How it still outputs 101101?!

    write('Enter decimal number: ');
    readln(dec);
    repeat 
    if (dec mod 2 = 0) then x:= '0' 
    else x:= '1'; 
    bin:= bin + x; 
    dec:= dec div 2;
    until dec= 0; 
    writeln(bin);
Was it helpful?

Solution

Check out this line:

5 div 2 = 4

It equals 2, not 4.

You also have a typo here:

22 mod 2 = 1, x = "0"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top