如何在Brainfuck中读取多位数字

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

但我宁愿在单元格0中设置一个数字,然后自动将该数字乘以每个数字的正确次数。我最好该做什么?

2个回答

1

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

它包含了乘法算法,还有一个IF条件以及布尔比较(例如,检查用户是否按下回车键[字符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 ]

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

1
当我在 https://copy.sh/brainfuck/ 和 https://sange.fi/esoteric/brainfuck/impl/interp/i.html 线上测试时,这两个网站都无法停止。 - JSideris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接