因此,我一直在尝试nand2tetris,并开始了关于汇编语言的章节,以及如何使用和实现汇编语言。我成功地完成了mult.asm,并想挑战自己,尝试创建一个代码,该代码可以为用户的任何输入找到数字的阶乘输出,到目前为止,这都是我的代码。
// ================================= Factorial ==================================
// This program calculates the Factorial F of a given number n
// At run time:
// - The user should enter the value of n into R0. R0.e. RAM[0]
// - The program then calculate the factorial of n R0.e. F(n)=n!
// F(n) = n*(n-1)*(n-2)*......*2*1
// - The result F(n) should be saved in RAM[1]
// -- You should also consider the F(0) case.
// ==============================================================================
// put your code here
//set tracker for current loop
@R1
M=0
@R2
M=1
@R3
M=0
@R4
M=0
@R5
M=0
@R6
M=0
(LOOP)
@R6
D=M //D=R6
@R1
M=M+D
@R2
D=M //D = R2
@R4
M=D //R4 = R2
@R0
D=D-M //D = R2 - R0
@END
D;JGE //If (R2-R0) > 0 goto END
@STEP
D;JLT //If (R2-R0) < 0 goto STEP
(STEP)
//Multiplication begins
// Gets R4 from R6.
@R6
D=M // wrting data of r6 into d register
// Add R1 to it.
@R1
D=D+M
// And write the result back to R6.
@R6
M=D
// Reduce R4 by 1.
@R4
D=M-1
M=D
// If R4 is still > 0 then loop.
@STEP
D;JGT
//Multiplication ends
@R2
M=M+1 //R2++
@LOOP
0;JMP //Got LOOP
(END)
@END
0;JMP //Infinite loop现在我遇到的问题是,循环工作,我的循环执行乘法循环的计数器在正确的时间停止,但是输出比预期的要高一些。那就是当我进入3!它推出了8而不是6。任何建议都将是伟大的感谢!
我试图得到我输入的任意数字的阶乘输出,计数器工作正常,并在正确的时间停止,但是最后的输出是错误的。
发布于 2022-11-26 13:03:23
一些一般性意见:
!
https://stackoverflow.com/questions/74579941
复制相似问题