简体   繁体   English

计算数字的平方并将其存储在组件8086中的dw中

[英]Calculate square of number and store them in dw in assembly 8086 masm

I am trying to calculate the square of 5 using brute force, so I tried this but it does not store anything in dw and I define dw like this result dw 2 dup(?) 我正在尝试使用蛮力计算5的平方,所以我尝试了一下,但是它没有在dw存储任何内容,因此我定义了dw像这样的result dw 2 dup(?)

mov ax, 5
mov bx, 5
mov cx, 1
mov dx, ax
loop1:
 add ax, dx

 cmp bx, cx
 je endLoop

 add cx, 1
 jmp loop1

endLoop:
 mov result, ax

calculate the square of 5 计算5的平方

5^2 = 25 but your code produces 30 5 ^ 2 = 25,但您的代码产生30

Your loop does 5 additions in total (1x in the fallthrough and 4x in the jump back). 您的循环总共进行了5次加法(结果下降1倍,回跳4倍)。
Since AX starts out with its original value, you get too much! 由于AX以其原始值开始,因此您获得了太多!

Either start AX at zero or do 1 iteration less: 从零开始AX或减少1迭代:

 mov ax, 5
 mov bx, 5
 mov cx, 1
 mov dx, ax
 XOR AX, AX   ; start at zero
loop1:
 add ax, dx

 cmp bx, cx
 je endLoop

 add cx, 1
 jmp loop1

- -

 mov ax, 5
 mov bx, 5
 mov cx, 1+1  ; one iteration less
 mov dx, ax
loop1:
 add ax, dx

 cmp bx, cx
 je endLoop

 add cx, 1
 jmp loop1

it does not store anything in dw and I define dw like this result dw 2 dup(?) 它不存储任何东西在dw ,我定义dw就是这样的result dw 2 dup(?)

Make sure to setup DS with code like this: 确保使用以下代码设置DS

mov ax, data    ; maybe you'll need 'mov ax, @data'
mov ds, ax

Try an alternative memory addressing using square brackets: 尝试使用方括号替代内存寻址:

mov [result], ax

From comment: 来自评论:

i am trying to retrieve the result like this 我正在尝试像这样检索结果
lea si, result
inc si
mov dl, [si]
mov ah, 2h
int 21h

Why do you fetch the second byte of the result? 为什么要获取结果的第二个字节? That will probably be plain zero. 那可能是零。
Moreover the result has 2 digits, therefore you need to ouput 2 characters. 而且结果有2位数字,因此您需要输出2个字符。

This is a solution from one of my other recent answers: 这是我最近其他回答之一的解决方案:

mov ax, [result]     ; AX=25
mov bl, 10
div bl               ; AL=2   AH=5
add ax, "00"         ; AL='2' AH='5'
mov dx, ax
mov ah, 02h
int 21h              ; Outputs the character in DL='2'
mov dl, dh
mov ah, 02h
int 21h              ; Outputs the character in DL='5'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM