Why won't the program print the sum of the array?

大城市里の小女人 提交于 2019-12-31 03:21:08

问题


So I'm building a simple 8086 Assembly program that allows the user to input 4 digits, store them in an array and print out the sum of those digits (The sum must be a one digit number):

data segment

    i db ?
    array db 20 dup(?)
    sum db ?

ends

stack segment

    dw 128 dup(0)

ends

code segment

    mov ax, data
    mov ds, ax
    mov es, ax

    mov i, 0

Enter:
    mov ah, 1
    int 21h
    mov bl, i
    mov bh, 0

    mov array[bx], al

    inc i
    cmp i, 4
    jne Enter

    mov sum, 0
    mov i, 0

Calc:
    mov bl, i
    mov bh, 0
    mov al, array[bx]

    add sum, al

    inc i
    cmp i, 4
    jne Calc

    mov dl, sum
    mov ah, 2
    int 21h

    mov ax, 4c00h
    int 21h

ends

However when I input the numbers 1 1 2 5 instead of giving me 9 it gives me some random character.

Any ideas?


回答1:


The DOS character input function gives you characters.
When you key in 1 DOS presents you with AL='1' meaning you get 49 where you might expect 1.
When you key in 2 DOS presents you with AL='2' meaning you get 50 where you might expect 2.
When you key in 5 DOS presents you with AL='5' meaning you get 53 where you might expect 5.
That's why we subtract 48 in these cases.

Enter:
    mov ah, 1
    int 21h
    mov bl, i
    mov bh, 0
    SUB AL, '0'        ;Same as SUB AL, 48
    mov array[bx], al

This way your array will contain the values 1, 1, 2, and 5 (No longer the characters '1', '1', '2', and '5')

Now you can safely do the additions, yielding 9.

Because sum now holds the value 9, but you need the character '9', you simple add 48 to do the conversion:

    mov dl, sum
    ADD DL, '0'        ;Same as ADD DL, 48
    mov ah, 02h
    int 21h


来源:https://stackoverflow.com/questions/53252525/why-wont-the-program-print-the-sum-of-the-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!