以下代码应该添加两个一维矩阵并显示总和。当程序获取第二个矩阵的输入时出现问题:rd_next循环永远不会结束。然而,第一个矩阵的输入就好了。
data_seg segment
mat1 dw 3 dup(?)
mat2 dw 3 dup(?)
n db 3
ten dw 10
counter db ?
string db 10 dup(?)
msg1 db 10,13,"Enter first matrix: ","$"
msg2 db 10,13,"Enter second matrix: ","$"
msg3 db 10,13,"Enter a number: ","$"
data_seg ends
code_seg segment
assume cs:code_seg,ds:data_seg
print_string proc
pop si
pop dx
mov ah,9
int 21h
push si
ret
print_string endp
read_char proc
pop di
mov ah,1
int 21h
mov ah,0
push ax
push di
ret
read_char endp
read_number proc
pop si
mov bx,0
mov dx,0
next_digit:
call read_char
pop ax
cmp al,0Dh
je done
sub al,30h
mov cl,al
mov ch,0
mov ax,bx
mul ten
add ax,cx
mov bx,ax
jmp next_digit
done: push bx
push si
ret
read_number endp
print_number proc
pop si
pop ax
mov bx,0
mov dx,0
repeat1:
mov cx,0
mov dx,0
div ten
push dx
inc counter
cmp ax,0
jne repeat1
print_digit:
pop dx
add dl,30h
mov ah,2
int 21h
dec counter
jnz print_digit
push si
ret
print_number endp
start:
mov ax,data_seg
mov ds,ax
mov al,n
mov counter,al ; initialize counter variable
mov bp,offset mat1 ; initialize pointer to first matrix
push offset msg1 ; prompt user to enter first matrix
call print_string
rd_next:
push offset msg3 ; prompt user for next number in matrix
call print_string
call read_number ; call the read_number procedure.
pop dx
mov [bp],dx
add bp,2
dec counter
jnz rd_next ; loop back to read the next number.
mov counter,al ; reset counter variable
mov bp,offset mat2 ; initialize pointer to second matrix
push offset msg2 ; prompt user to enter second matrix
call print_string
jmp rd_next
mov al,n
mov si,offset mat1
mov di,offset mat2
matrixsum:
mov bx,[si]
mov cx,[di]
add bx,cx
push bx
call print_number
inc si
inc di
dec al
jnz matrixsum
code_seg ends
end start
我没有看到代码有什么问题。我尝试创建一个单独的rd_next2循环来获取第二个矩阵的输入,但它不起作用。
答案 0 :(得分:1)
哦,它会结束,只需要一些时间,因为你忘了重新初始化counter
。将初始化代码移到rd_next
内,例如:
mov bp,offset mat1 ; initialize pointer to first matrix
push offset msg1 ; prompt user to enter first matrix
call print_string
rd_next:
mov al,n
mov counter,al ; initialize counter variable
学习使用调试器,这样您就可以单步执行代码,看看它为什么会这样做。
PS:你有一种巧妙的方法可以从函数中返回结果,但请不要这样做:D只需像其他人一样使用寄存器。