检测添加溢出

时间:2015-02-03 00:13:31

标签: overflow add mips detect

在mips代码中发生溢出的时候检查什么是一个好的循环?这是我通过基本上向账户添加存款来平衡支票簿的程序。发生溢出时,我只是不断获取不正确的值。我需要一个循环来检测如果接受该值就会发生溢出,然后在不接受错误值的情况下请求另一个值。

# Functional Description:
# This program can be used to balance your check book.
# <DESCRIBE OVERFLOW FEATURE HERE>
#####################################################################
# Pseudocode:
# Print Header;
#   s0 = 0;
# loop: Prompt user for transaction;
#   v0 << transaction amount;
#   if (v0 = 0) done;
#   s0 = s0 + v0;
#  PSEUDOCODE FOR OVERFLOW DETECTION ALGORITHM HERE>
#   cout << s0
#   go to loop
# done:
# cout << "Adios Amigo"
# 
######################################################################
# Register Usage:
# $v0: Transaction Amount
# $s0: Current Bank Balance
#   <HERE YOU DECLARE ANY ADDITIONAL REGISTERS USED>
######################################################################
.data    # Data declaration section
Head: .ascii    "\n\tThis program, written by <YOUR NAME>,"
.ascii  " can be used to balance your check book."
.asciiz "\n\n\t\t\t\t\t\t\t\t\t  Balance"
tabs:   .asciiz "\t\t\t\t\t\t\t\t\t"
tran:   .asciiz "\nTransaction:"
bye:    .asciiz "\n  ****  Adios Amigo  **** "

.text    # Executable code follows
main:
li  $v0, 4   # system call code for print_string
la  $a0, Head    # load address of Header message into $a0
syscall  # print the Header

move    $s0, $zero   # Set Bank Balance to zero
loop:
li  $v0, 4   # system call code for print_string
la  $a0, tran    # load address of prompt into $a0
syscall  # print the prompt message

li  $v0, 5   # system call code for read_integer
syscall  # reads the amount of  Transaction into $v0

beqz    $v0, done    # If $v0 equals zero, branch to done
addu $s0, $s0, $v0  # add transaction amount to the 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

done:   li  $v0, 4   # system call code for print_string
la  $a0, bye     # load address of msg. into $a0
syscall  # print the string

li  $v0, 10  # terminate program run and
syscall  # return control to system

# END OF PROGRAM

1 个答案:

答案 0 :(得分:0)

如果将两个正数加在一起且结果小于零,即结果的第31位置位,则发生溢出。如果将两个负数相加并且结果大于零,则会发生溢出。如果添加正数和负数,则不会发生溢出。