Mips 程序集 查找用户创建的数组的最大值



我的CS-250计算机组织和体系结构课程已经上了几周,我们目前正在学习MIPS汇编语言。我正在尝试获取用户输入的数组并找到该数组中的最大数字。我不太明白在这种情况下如何使用slt关键字,因为这是我们的教授希望我们做的。

这是我当前的代码。如果您有任何建议,我对这些想法非常开放。我目前唯一的空白点是用于查找数组最大值的函数。

.globl main
.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "
.text
main:
#Loading array into $t5
la $t5, array
li $s0, 0
li $v0, 4
la $a0, prompt
syscall
li $v0, 5
syscall
move $s1, $v0
Loop: 
#Asking the user for input
li $v0, 4
la $a0, input
syscall
#Storing user input in array address in $t5
li $v0, 5
syscall
sw $v0, 0($t5)
#Counting iterations for the loop as well as the array address
addi $s0, $s0, 1
addi $t5, $t5, 4
#Loop Exit
beq $s0, $s1, Maximum
j Loop
Maximum: 

Exit: 
li $v0, 10
syscall

这应该可以完成这项工作:

.globl main
.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "
.text
main:
#Loading array into $t5
la $t5, array
li $s0, 0
li $v0, 4
la $a0, prompt
syscall
li $v0, 5
syscall
move $s1, $v0
Loop: 
#Asking the user for input
li $v0, 4
la $a0, input
syscall
#Storing user input in array address in $t5
li $v0, 5
syscall
sw $v0, 0($t5)
#Counting iterations for the loop as well as the array address
addi $s0, $s0, 1
addi $t5, $t5, 4
#Loop Exit
beq $s0, $s1, Maximum
j Loop
Maximum:
la $t5, array # load the array start address
lw $t2, 0($t5) # max = first element
li $s0, 0 # i = 0
Max_loop:
lw $t3, 0($t5) # temp = actual array element
slt $t4, $t2, $t3 # max < temp ?
bne $t4, 1, Else # jump to else branch if it condition is false
move $t2, $t3 # condition was true let max = temp
Else:
addi $s0, $s0, 1 # i++
addi $t5, $t5, 4 # array += 4
beq $s0, $s1, Exit # i < num
j Max_loop
Exit: 
li $v0, 10
syscall

一切似乎都可以在 MARS 4.5 MIPS 模拟器中正常工作。结果在退出时$t2。如果需要,您可以轻松添加代码以打印其值。

slt $t1, $t2, $t3基本上会像代码一样在 C 中执行此操作:

if ($t2 < $t3)
$t1 = 1
else
$t1 = 0

因此,基于它,您可以使用它的结果实现条件分支。

请注意,我提供的代码不一定是最佳的,如果用户输入小于1,可能会出现问题,但无论如何都应该在输入阶段检查。

最新更新