16

我想用 bf 读取任意位数的数字。如果我手动设置,我知道如何读取正确的位数,如下所示:

,>,>, 2 Read in 3 digits
<< 0
--------
--------
--------
--------
--------
-------- 45 decrements
> 1
--------
--------
--------
--------
--------
--------
> 2
--------
--------
--------
--------
--------
--------

[>+<-]< 1 Copy digit 3 to cell 3

[>>++++++++++<<-]< Copy 10 * digit 2 to cell 3

Copy 100 * digit 1 to cell 3
[>>>>++++++++++ 4
    [<++++++++++>-] 4
<<<<-]>>> 3

>++++++++++..< Add 2 line breaks

., Print and Pause

但我宁愿能够设置一个数字,cell 0然后为每个数字自动乘以正确的次数。我最好做什么?

4

2 回答 2

1

这个链接应该很有帮助:http ://esolangs.org/wiki/brainfuck_algorithms

它包含乘法算法以及 IF 条件以及布尔比较(例如,检查用户是否按下了 enter [character 10] 以结束输入。)

然后你要做的就是这个(我将编写一些伪代码,然后由你使用那里描述的算法来实现它)。我会告诉你最后给出如何实现一个while循环的伪代码,因为它不包含在该页面中(但非常简单......相对而言)。当您设法准确了解每个角色在做什么时,您一定会感到惊讶:D。无论如何,这里是:

你需要两个单元格 A 和 B

move to B
input a character
while B is not equal to 10 (the newline character) then
    subtract 48 from B ('0' is character 48, so if we subtract 48 from any digit entered we should get its value. Of course this assumes that the user only presses digit keys or enter. I'll leave it as an exercise to you to do error checking)
    multiply A by 10
    add B to A (you can just move B to A like this [<+>-] since you will not need B's value anymore)
    move to B
    input a character

这里有一些关于如何创建 while 循环的信息。假设您有以下代码:while (condition) {body}. 我将假设您设法使用我之前给您的链接实现了条件的代码。您需要一个存储条件结果的单元格,我将调用它C

execute condition and store result in C
start loop using [[-] (start the loop and immediately clear C)
    execute loop body
    execute condition and store result in C
end loop using ]
于 2012-11-27T12:09:50.777 回答
0

这个程序是读取n位数字并打印出来。始终保持 n 位数字的最佳方法是将 ascii 作为序列存储在磁带中。

> +
[ - >,>+< 
  ----- -----    ; minus 10
  [              ; if enters means it is not a \n
    +++++ +++++  ; restore prev value
    < 
  ] >>           ; moving forward
]
                 ; numbers are 0 0 49 0 50 0 51
                 ; for input 123
<<<<[<<]         ; moving to the beginning
>>               ; reaching first char
[.>>]            ; just printing till end
于 2013-10-18T16:00:12.653 回答