【问题标题】:MIPS Program that shows the lowest of 3 user-inputted integers, doesn't register negative numbersMIPS 程序显示 3 个用户输入的整数中的最小值,不记录负数
【发布时间】:2021-01-16 17:10:35
【问题描述】:

我的代码能够正确编译,它确实找到了最小的正整数,但它似乎无法正确检测到负号。我想也许我需要使用签名命令,但我找不到可能需要更改的命令。有什么想法吗?

.data 
prompt1: .asciiz "Enter an integer: " 
prompt2: .asciiz "Enter an integer: " 
prompt3: .asciiz "Enter an integer: " 
smallest: .asciiz "\nThe smallest integer is: "

.text

li $v0, 4 
la $a0, prompt1 
syscall 

li $v0, 5 
syscall 
move $t0,$v0 

li $v0, 4 
la $a0, prompt2 
syscall 

li $v0, 5 
syscall 
move $t1,$v0 

li $v0, 4 
la $a0, prompt3 
syscall 

li $v0, 5 
syscall 
move $t2,$v0 

blt $t1, $t0, Num1 
move $t1, $t0 

Num1: 
blt $t2, $t1, Num2
move $t2, $t1

Num2:  
li $v0, 4  
la $a0, smallest 
syscall 

li $v0, 1 
move $a0, $t1 
syscall 

li $v0, 10
syscall

【问题讨论】:

  • blt 是有符号比较。 bltu 将是未签名的。您确定您的输入系统调用处理签名输入吗?检查 MARS 文档,并使用调试器单步执行并查看寄存器值,以确保寄存器中的数字是您输入的。如果不是,那就是输入问题。
  • 问题不是 neg/pos,而是更根本的问题:第三个最小的数字没有得到正确处理。尝试输入765,程序说6是最小的。

标签: assembly input integer mips negative-number


【解决方案1】:

问题不是负数,而是$t2 没有正确移动到结果中。逻辑和标签似乎有点难以理解。我会将结果存储在$t0 中,然后编写将每次试验的最小值设置为$t0 的分支。

# ... same as above ...

    # t0 = min(t0, t1)
    blt $t0, $t1, runoff
    move $t0, $t1

runoff:
    # t0 = min(t0, t2)
    blt $t0, $t2, done
    move $t0, $t2

done:
    li $v0, 4
    la $a0, smallest
    syscall

    li $v0, 1
    move $a0, $t0
    syscall

    li $v0, 10
    syscall

一些测试来帮助确保这个工作(子流程代码归功于this post):

import itertools
from subprocess import Popen, PIPE

def start(cmd):
    return Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)

def read(process):
    return process.stdout.read().decode("utf-8")

def write(process, s):
    process.stdin.write(f"{s}\n".encode("utf-8"))
    process.stdin.flush()

def terminate(process):
    process.stdin.close()
    process.terminate()
    process.wait(timeout=0.2)

def run_test(mips_prog, inputs, should_endwith):
    process = start(["spim", "-f", mips_prog])

    for num in nums:
        write(process, num)

    assert read(process).endswith(should_endwith)
    terminate(process)

if __name__ == "__main__":
    for nums in itertools.permutations("345"):
        run_test("min_of_3_nums.s", nums, "The smallest integer is: 3")

    for nums in itertools.permutations(["-3", "-2", "-1"]):
        run_test("min_of_3_nums.s", nums, "The smallest integer is: -3")

    for nums in itertools.permutations(["-4", "-4", "-1"]):
        run_test("min_of_3_nums.s", nums, "The smallest integer is: -4")

    for nums in itertools.permutations("667"):
        run_test("min_of_3_nums.s", nums, "The smallest integer is: 6")

【讨论】:

  • 谢谢,这帮了大忙!我已经意识到 $t2 没有正确存储,但不是很具体的部分需要更改。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2015-07-30
相关资源
最近更新 更多