How to calculate the sum of 2 numbers with BrainFuck

前端 未结 7 728
独厮守ぢ
独厮守ぢ 2020-12-09 06:01

I\'m trying to write a program with BrainFuck that can read two numbers up to 9, calculate the sum of them and then print the result out, e.g. 3 & 5 give the result 8 .

7条回答
  •  粉色の甜心
    2020-12-09 06:44

    Think of the language as a huge tape (30K bytes long) where you can read, write and move forward or backward and increment/decrement one cell at a time (each cell being 1 byte, so you effectively have 30K cells). Optionally, you can read in and write out stuff that the byte stream holds(in ASCII form). Assuming that you know the basic operators, a program to sum two numbers should go along the following lines:

    ,       ; read character and store it in p1
    >       ; move pointer to p2 (second byte)
    ,       ; read character and store it in p2
    [           ; enter loop
        <       ; move to p1
        +       ; increment p1
        >       ; move to p2
        -       ; decrement p2
    ]           ; we exit the loop when the last cell is empty
    <       ; go back to p1
    ------------------------------------------------ ; subtract 48 (ie ASCII char code of '0')
    .       ; print p1
    

提交回复
热议问题