在 MIPS 中具有两个条件的 While 循环
While Loop with two conditions in MIPS
我最近在学习 MIPs 汇编语言,我被要求在作业中用 MIPS 实现以下 C 代码。
int i = 0;
int j = 10;
while(i < 5 && j >= 5)
{
int sum = i+j;
printf(“%d ”, sum);
i++;
j--;
}
我不明白如何在 MIPS 中实现带有两个条件的 while 循环?
我已经为你写了这段代码:
.data
space: .asciiz " "
.text
.globl main
.ent main
main:
li $t0, 0 #store i's value in $t0
li $t1, 10 #store j's value in $t1
li $t6, 5
j while
.end main
#while loop
while:
sge $t2, $t0, $t6 #$t2=1(true) if i>=5
slt $t3, $t1, $t6 #$t3=1(true) if j<5
or $t4, $t3, $t2
beq $t4, 1, exit #exit, if $t4=1(true)
add $t5, $t1, $t0 #sum of i and j
#printing sum
li $v0, 1
move $a0, $t5
syscall
li $v0, 4
la $a0, space
syscall
add $t0, $t0, 1 #incrementing i
sub, $t1, $t1, 1 #decrementing j
j while
.end while
exit:
li $v0, 10
syscall
sge(设置大于等于)和slt(设置小于)指令是我曾经执行过的比较指令两个条件的否定,以便我的代码知道何时退出 while 循环。使用sge slt指令实现的两个条件的布尔值分别存储在$t2和$t3寄存器中。使用 or 指令是因为德摩根定律 (!(A and B) = !A or !B) 用于两个条件的最终布尔值。 beq指令用于将两个条件作为一个整体来判断是继续还是终止while循环。如果要继续循环,则计算并打印 i 和 j 的总和,然后使用 add 和 sub 递增 i 并递减 j instructions.'j while' 指令在最后确保 while 循环保持 运行 直到条件不再满足。
代码中添加了注释,以确保您理解我所做的正确事情。我鼓励您在此处阅读有关我使用的指令和其他 MIPS 指令的更多信息:https://www.cs.tufts.edu/comp/140/lectures/Day_3/mips_summary.pdf
希望这对您有所帮助!
我最近在学习 MIPs 汇编语言,我被要求在作业中用 MIPS 实现以下 C 代码。
int i = 0;
int j = 10;
while(i < 5 && j >= 5)
{
int sum = i+j;
printf(“%d ”, sum);
i++;
j--;
}
我不明白如何在 MIPS 中实现带有两个条件的 while 循环?
我已经为你写了这段代码:
.data
space: .asciiz " "
.text
.globl main
.ent main
main:
li $t0, 0 #store i's value in $t0
li $t1, 10 #store j's value in $t1
li $t6, 5
j while
.end main
#while loop
while:
sge $t2, $t0, $t6 #$t2=1(true) if i>=5
slt $t3, $t1, $t6 #$t3=1(true) if j<5
or $t4, $t3, $t2
beq $t4, 1, exit #exit, if $t4=1(true)
add $t5, $t1, $t0 #sum of i and j
#printing sum
li $v0, 1
move $a0, $t5
syscall
li $v0, 4
la $a0, space
syscall
add $t0, $t0, 1 #incrementing i
sub, $t1, $t1, 1 #decrementing j
j while
.end while
exit:
li $v0, 10
syscall
sge(设置大于等于)和slt(设置小于)指令是我曾经执行过的比较指令两个条件的否定,以便我的代码知道何时退出 while 循环。使用sge slt指令实现的两个条件的布尔值分别存储在$t2和$t3寄存器中。使用 or 指令是因为德摩根定律 (!(A and B) = !A or !B) 用于两个条件的最终布尔值。 beq指令用于将两个条件作为一个整体来判断是继续还是终止while循环。如果要继续循环,则计算并打印 i 和 j 的总和,然后使用 add 和 sub 递增 i 并递减 j instructions.'j while' 指令在最后确保 while 循环保持 运行 直到条件不再满足。 代码中添加了注释,以确保您理解我所做的正确事情。我鼓励您在此处阅读有关我使用的指令和其他 MIPS 指令的更多信息:https://www.cs.tufts.edu/comp/140/lectures/Day_3/mips_summary.pdf
希望这对您有所帮助!