汇编程序使用条件跳转添加奇数

Assembly program to add odd numbers using conditional jump

我有一个任务:

Write an Assembly code to add following fifteen odd numbers with using conditional jump.

奇数: 3, 5, 7, 9, 11, 13, 15, 17, 19, 21,23,25,27,29,31

我做了这个解决方案。我想检查一下这里面有什么问题...

[org 0x0100]
mov bx, num1
mov cx, 15
mov ax, 0
li:
add ax, [bx]
add bx, 2
sub cx, 1
jnz li
mov ax, 0x4c00
int 0x21
num1: dw 3, 5, 7, 9, 11, 13, 15, 17, 19, 21,23,25,27,29,31

这当然是 一种 方法,您唯一需要注意的是您在 ax 中累积总和,但随后您使用 int 21, fn 4c.

退出程序时覆盖 ax

巧合的是,这些数字总和为 255,因此它实际上 适合 al,这是用于 return 代码的寄存器被那个中断(见Ralf Brown's excellent interrupt list)。

DOS 是否会用它做任何智能的事情,我不能说:-)

为了在退出程序时保留 al,只需改为:

mov  ah, 0x4c
int  0x21

您可能要考虑做的另一件事是直接打印项目而不是 returning。下面的代码显示了如何使用我的工具库中的函数来执行此操作,该函数能够将 al 寄存器输出为十进制值:

        org     00100h

        mov     bx, num1
        mov     cx, 15
        mov     ax, 0
li:
        add     ax, [bx]
        add     bx, 2
        sub     cx, 1
        jnz     li

        call    prt_byte

        mov     ah, 04ch
        int     021h

num1:   dw      3, 5, 7, 9, 11, 13, 15, 17, 19, 21,23,25,27,29,31
eoln:   db      0dh, 0ah, '$'

prt_byte:
        push    ax
        push    bx
        push    dx

        cmp     ax, 100
        jl      skip_h

        push    ax

        mov     bl, 100             ; divide ax by 100.
        div     bl
        mov     ah, 0

        call    prt_digit

        mul     bl                  ; remove hundreds digit.
        mov     bx, ax
        pop     ax
        sub     ax, bx

skip_h:
        cmp     ax, 10
        jl      skip_t

        push    ax

        mov     bl, 10              ; divide ax by 10.
        div     bl
        mov     ah, 0

        call    prt_digit

        mul     bl                  ; remove tens digit.
        mov     bx, ax
        pop     ax
        sub     ax, bx

skip_t:
        call    prt_digit

        mov     dx, offset eoln
        mov     ah, 9
        int     021h

        pop     dx
        pop     bx
        pop     ax
        ret

prt_digit:
        push    ax                  ; save registers.
        push    dx

        mov     dx, ax              ; put in correct register.
        add     dx, '0'             ; turn into digit.
        mov     ah, 2               ; print.
        int     021h

        pop     dx                  ; restore registers and return.
        pop     ax
        ret