汇编语言(二十一)之数值交换与自增
输入两个数,如果第一个数为偶数第二个数为奇数,互换位置;如果两个数都是奇数,则两个数都加一
程序运行:
代码:
datas segment
A dw 0
B dw 0
a_string db 0ffh, 0 ,100h dup(?)
b_string db 0ffh, 0 ,100h dup(?)
inputA db 'input A=$'
inputB db 0dh,0ah,'input B=$'
error_number db 0dh,0ah,'error number$'
outputA db 0dh,0ah,'A=$'
outputB db 0dh,0ah,'B=$'
datas ends
stacks segment stack
db 100h dup(?)
stacks ends
codes segment
assume cs:codes,ds:datas,ss:stacks
main proc far
start:
push ds
mov ax,0h
push ax
mov ax,datas ;初始化ds
mov ds,ax
;输入a提示
lea dx,inputA
mov ah,9
int 21h
;输入a
lea dx,a_string
mov ah,10
int 21h
;a转成十进制数
lea si,a_string+1
call translate_to_number
mov A,ax
;输入b提示
lea dx,inputB
mov ah,9
int 21h
;输入b
lea dx,b_string
mov ah,10
int 21h
;b转成十进制数
lea si,b_string+1
call translate_to_number
mov B,ax
;将A、B移至ax,bx
mov ax,A
mov bx,B
test ax,1 ;判断ax是否为偶数
jz even_number ;若为偶数,跳转
test bx,1 ;判断bx是否为偶数
jz next ;若为偶数,跳转
inc ax ;否则,ax++,bx++
inc bx
jmp next ;跳转
even_number:
test bx,1 ;判断bx是否为偶数
jz next ;若为偶数,跳转
xchg ax,bx ;将奇数移至ax
next:
mov A,ax ;保存ax,bx
mov B,bx
lea dx,outputA ;输出A、B
mov ah,9
int 21h
mov ax,A
call decimal
lea dx,outputB
mov ah,9
int 21h
mov ax,B
call decimal
ret
main endp
;字符串转换为十进制数
translate_to_number proc near
;si:lenght first
push cx
push dx
push bx
push si
push di
mov di,10
mov ax,0
mov cl,[si]
mov ch,0
cmp cx,0
jz err
inc si
tran:
mov bl,[si]
inc si
cmp bl,'0'
jb err
cmp bl,'9'
ja err
sub bl,30h
xor bh,bh
mul di
add ax,bx
loop tran
jmp exit
err:
lea dx,error_number
mov ah,9
int 21h
mov ax,4c00h
int 21h
exit:
pop di
pop si
pop bx
pop dx
pop cx
ret
translate_to_number endp
decimal proc near
push ax
push cx
push dx
push bx
cmp ax,0
jge plus
mov bx,ax
mov dl,'-'
mov ah,2
int 21h
neg bx
mov ax,bx
plus:
mov cx,0
mov bx,10
de:
xor dx,dx
div bx
push dx
inc cx
cmp ax,0
jnz de
de1:
pop dx
add dl,30h
mov ah,2
int 21h
loop de1
pop bx
pop dx
pop cx
pop ax
ret
decimal endp
codes ends
end main