因此,我在mars程序集中有一个小程序,它得到了最大的公共因子:
.text
addiu $4,$zero,49
addiu $5,$zero,42
add $2,$zero,$5
beq $4,$zero,label10
loop:
beq $5,$zero,label9
slt $9,$5,$4
bne $9,$zero,if
slt $10,$4,$5
bne $10,$zero,else
beq $10,$zero,else##if $4 and $5 are equal.
if:
sub $4,$4,$5
j endif
else:
sub $5,$5,$4
j endif
endif:
j loop
label9:
add $2,$0,$4
label10:结果将保存在寄存器2。现在我的第二个任务是,我应该改变我的程序,使我的算法是一些“函数”(子程序),您可以设置参数寄存器4和5和返回值在寄存器2。我现在的问题是,我不知道如何做。
发布于 2022-06-07 17:57:16
下面是如何将代码片段转换为函数的方法:
MyFunc.
jr $ra..text部分的开头--您希望这个测试main是模拟器首先运行的,所以它会调用您的函数--您不想首先调用您的函数,因为它不再是一个片段,而是现在是一个函数,它应该被正确地调用:通过传递参数和返回地址。主程序也必须正确地终止程序,否则它将从边缘运行并再次运行该函数,但这次是意外的。。
.text
# test main: call MyFunc
#
# call function, pass some parameters
li $a0, 20 # load first arg register
li $a1, 15 # load second arg register
jal MyFunc # the actual invocation
# this jumps to the function,
# while also passing the return address in $ra
# here's where come back to when the function is done:
move $a0, $v0 # move return value into $a0, so we can print it
li $v0, 1 # and print
syscall
li $v0, 10 # and stop the program
syscall
#
#
#
MyFunc: # start of MyFunc
# ... # code of function goes here
jr $ra # jump back to the caller by using the return address register建议使用友好的注册名,而不是简单的数字名称。(而且我们不应该在同一个程序中将友好名称和简单数字名称混为一谈。)
https://stackoverflow.com/questions/72521912
复制相似问题