MIPS 程序显示 3 个用户输入整数中最小的一个,不记录负数

问题描述 投票:0回答:1

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

.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
assembly input integer mips negative-number
1个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.