程序为什么不打印数组的和? [英] Why won't the program print the sum of the array?

查看:68
本文介绍了程序为什么不打印数组的和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在构建一个简单的8086汇编程序,该程序允许用户输入4位数字,将它们存储在数组中并打印出这些数字的总和(总和必须为一位数字):

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

但是,当我输入数字1 1 2 5而不是给我9时,它会给我一些随机字符.

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

有什么想法吗?

推荐答案

DOS字符输入功能为您提供字符.
当您键入 1 时,DOS会为您提供AL='1',这意味着您可能期望得到1的地方为49.
当您键入 2 时,DOS会为您提供AL='2',这意味着您将获得50,而您可能会期望2.
当您键入 5 时,DOS会为您提供AL='5',这意味着您可以得到53,而您可能期望5.
这就是为什么在这种情况下我们要减去48.

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

这样,您的数组将包含值1、1、2和5(不再包含字符"1","1","2"和"5")

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

现在您可以安全地进行加法了,得到9.

Now you can safely do the additions, yielding 9.

由于 sum 现在拥有值9,但是您需要字符'9',因此只需添加48即可进行转换:

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

这篇关于程序为什么不打印数组的和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆