汇编语言(二十二)之统计减去奇数的个数
输入一个正数,该数减去递增奇数(从1开始)直至小于等于零为止,计算该数减去奇数的个数
程序运行:
代码:
datas segment
NUM dw 17
ANS dw 0
NUM_string db 0ffh, 0 ,100 dup(?)
inputNUM db 'input NUM=$'
error_number db 0dh,0ah,'error number$'
outputANS db 0dh,0ah,'ANS=$'
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,inputNUM
mov ah,9
int 21h
;输入a
lea dx,NUM_string
mov ah,10
int 21h
;a转成十进制数
lea si,NUM_string+1
call translate_to_number
mov NUM,ax
;mov ax,NUM
mov bx,1
mov cx,0
s:
sub ax,bx ;减去奇数
inc cx
add bx,2 ;奇数加2
cmp ax,0 ;判断ax是否大于0
jg s ;若大于0,循环继续
mov ANS,cx
lea dx,outputANS ;输出ANS
mov ah,9
int 21h
mov ax,ANS
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