【问题标题】:How to write a divide function that produces 0 if the divisor is 0?如果除数为0,如何编写产生0的除法函数?
【发布时间】:2019-01-27 13:03:03
【问题描述】:

如果它试图除以0,函数结果应该是0。

  org 100h
  mov al,b
  mov bl,c
  mov cl,0
  cmp bl,cl
  jmp posht;
  div bl
  mov ah,d
  mul ah
  mov ah,a
  sub ah,al
posht:
  mov al,0
  ret

a dw 10
b dw 8
c dw 4
d dw 2
zero dw 0

如何使这段代码在汇编语言 emu8086 上运行?

【问题讨论】:

  • 检查除数是否为0,如果是则返回0而不是除数。
  • org 100h mov al,b mov bl,c mov cl,0 cmp bl,cl jmp posht; div bl mov ah,d mul ah mov ah,a sub ah,al posht: mov al,0 ret a dw 10 b dw 8 c dw 4 d dw 2 zero dw 0 像这样?
  • 在评论中发布整个程序会使其不可读。你为什么不试试看它是否有效?
  • 对不起,我是这门语言的新手,我不太确定,但我认为它正在工作,谢谢
  • @TheHamshah 如果您有新代码,请将代码添加到您的问题中。评论不太适合这个。

标签: assembly x86-16 emu8086


【解决方案1】:
mov bl,c
mov cl,0
cmp bl,cl
jmp posht

若要在除数恰好为 0 时实际退出,您需要将这个无条件的 jmp 更改为有条件的:je(如果相等则跳转)。

在您可以进行(现在允许的)除法之前,您仍然需要清空AH 寄存器,因为div bl 指令将整除AX,而不仅仅是AL

您需要重新考虑您的函数如何报告其结果。目前,无论除数是否为零,AL 将始终报告等于 0。您将如何区分?

  mov ax, b    ; 8 Also defines AH
  mov bl, c    ; 4
  cmp bl, 0
  je  posht    ; Bail out on zero divisor
  div bl       ; 8 / 4 --> AL=2 AH=0
  mov ah, d    ; 2
  mul ah       ; 2 * 2 --> AX=4
  mov ah, a    ; 10
  sub ah, al   ; 10 - 4 --> AH=6
  ...          ; ?
  RET
posht:
  mov al, 0
  ret

【讨论】:

  • org 100h mov al,b mov bl,c cmp bl,0 je posht: div bl mov ah,d mul ah mov ah,a sub ah,al posht: mov al,0 ret a dw 20 b dw 8 c dw 4 d dw 4 这就是我经过一些编辑后的样子,所以现在可以了吗?
  • @TheHamshah 不行。首先重读九月的第二段关于使用AX 而不是AL。那就看看Sep的代码怎么有2条RET指令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 2023-03-25
  • 2020-10-20
相关资源
最近更新 更多