【问题标题】:Mips Assembly Finding the maximum value of a user-created arrayMips Assembly 查找用户创建数组的最大值
【发布时间】:2020-02-14 23:35:05
【问题描述】:

我已经参加了 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

【问题讨论】:

  • 我假设您已经拥有MIPS32™ 程序员架构第二卷:MIPS32™ 指令集。如果没有,您应该做的第一件事就是下载它。 SLT rd,rs,rt的描述为"将GPR rs和GPR rt的内容作为有符号整数进行比较,并将比较的布尔结果记录在GPR rd中。如果GPR rs小于GPR rt,则结果为1(真);否则为 0 (false)"。可以想象,可以将SLTBEQBNE 组合起来创建if (rs < rt)if (rs >= rt)。如果您想将输入视为无符号,还有一个 SLTU

标签: arrays integer max mips


【解决方案1】:

这应该可以完成工作:

.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,则可能会出现问题,但无论如何都应该在输入阶段进行检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多