我正在努力在 MIPS 中实现检测溢出并使用 addu 抛出错误。
这是学校作业。我们得到的代码是一个非常基本的银行分类账。分类账要求用户输入,如果输入为正,则添加到余额中,如果输入为负,则从余额中减去。我已经改进了它以根据分配检测非整数输入,现在我需要能够检测溢出并抛出错误消息,并且如果检测到溢出则不更改余额(然后重新提示交易)。我在这里想,因为这只是加法,如果符号相同并导致相反的符号,则存在溢出。我还认为,如果符号相反,则不会发生溢出。
目前它似乎直接跳过了我的溢出检测,因此它可以工作,但没有根据我的作业需要检测溢出。对我做错了什么有什么建议吗?
这是我的代码的相关部分:
loopB:
li $s1, 0 #### reset $s1
add $s1, $zero, $t3 #### load integer value into $s1
beqz $s1, done # If $s1 equals zero, branch to done
li $s2, 0 #### initialize $s2 for temporary balance
addu $s2, $s0, $t6 #### set temporary balance to initial balance
addu $s2, $s0, $s1 # add transaction amount to the temporary Balance
oTest:
sltiu $t6, $s0, 0 #### if $t6 == 1 then number is negative
sltiu $t7, $s1, 0 #### if $t7 == 1 then number is negative
bne $t6, $t7, LoopC #### if opposite signs then no overflow
sltiu $t8, $s2, 0 #### if $t8 == 1 then the number is negative
and $t9, $t6, $t7 #### if $t9 == 1 then $t6 and $t7 are both negative
bne $t9, $t8, over #### if $t9 and $t8 are not both negative, then overflow has occured
sgtu $t6, $s0, $zero #### if $t6 == 1 then number is positive
sgtu $t7, $s0, $zero #### if $t7 == 1 then number is positive
sgtu $t8, $s0, $zero #### if $t8 == 1 then number is positive
and $t9, $t6, $t7 #### if $t9 == 1 then $t6 and $t7 are both positive
bne $t9, $t8, over #### if $t8 and $t9 are not equal then overflow has occured
LoopC:
addu $s0, $s0, $s1 #### add transaction to balance
li $v0, 4 # system call code for print_string
la $a0, tabs # load address of tabs into $a0
syscall # used to space over to the Balance column
li $v0, 1 # system call code for print_integer
move $a0, $s0 # move Bank Balance value to $a0
syscall # print Bank Balance
b loop # branch to loop
over:
li $v0, 4 #### system call code for print_string
la $a0, oMsg #### load address of msg. into $a0
syscall #### print the string
li $s2, 0 #### reset $s2
li $v0, 1 #### system call code for print_integer
move $a0, $s0 #### move Bank Balance value to $a0
syscall #### print Bank Balance
b loop # branch to loop
你能解释一下你想在这里做什么吗:
addu $s2, $s0, $t6 #### set temporary balance to initial balance
addu $s2, $s0, $s1 # add transaction amount to the temporary Balance
?
这两条指令放在一起没有意义。第二个擦除/重置
$s2
而不使用第一个的结果。
您使用无符号比较来比较 0 的立即数 - 这将始终产生 false,因为根据无符号数的定义,没有无符号数小于零。换句话说,负数不是无符号数可能存在的属性。
如果您想知道数字是否为负数,请使用 signed 比较。
仅供参考,您还可以使用移位来提取或复制符号位,因此通过使用算术移位 31,得到 -1 或 0,并使用逻辑移位 32 得到 1 或 0。