【问题标题】:finding index of the array in tasm assembly language and printing it在 tasm 汇编语言中查找数组的索引并打印它
【发布时间】:2020-12-03 10:20:25
【问题描述】:

我制作了一个 tasm 汇编语言程序,它在用户输入的数组中找到最小值。我想找到程序找到的最小值的元素的索引。

我想找到程序找到的元素的索引。

例如:输入数组是[1,2,3,4,5,6]。它应该返回 1 作为最小值和 0 作为索引。

这里是代码。

Data Segment
 msg db 0dh,0ah,"Please enter the length of the array: $"
 msg1 db 0dh,0ah,"Enter a number: $"
 newl db 0dh,0ah," $"
 res db 0dh,0ah,"The minimum is: $"
 len db ?
 min db ?
Data ends
Code Segment
assume CS:Code,DS:Data
Start:
 mov ax,Data
 mov DS,ax

 mov dx,offset msg
 mov ah,09h
 int 21h
 
 call Accept

 mov len,bl
 mov cl,bl
 mov ch,00h

 mov di,1000h
 
back: mov dx,offset msg1
 mov ah,09h
 int 21h
 call Accept
 mov [di],bl
 inc di
 loop back

 mov di,1000h
 mov cl,len
 mov ch,00h

 mov dx,offset newl
 mov ah,09h
 int 21h

 mov al,[di] 
 mov min,al

chk: mov bl,min
 mov al,[di]
 cmp bl,al
 jc a
 mov min,al
 jmp b
a: mov min,bl
b: inc di
 loop chk

 mov dx,offset res
 mov ah,09h
 int 21h

 mov bl,min
 call DispNum

 mov ah,4ch
 int 21h
Accept proc
 mov ah,01h
 int 21h
 call AsciiToHex
 rol al,4
 mov bl,al
 mov ah,01h
 int 21h
 call AsciiToHex
 add bl,al
 ret
endp
DispNum proc
 mov dl,bl
 and dl,0f0h
 ror dl,4
 call HexToAscii
 mov ah,02h
 int 21h
 mov dl,bl
 and dl,0fh
 call HexToAscii
 mov ah,02h
 int 21h
endp
AsciiToHex proc
 cmp al,41h
 jc sk
 sub al,07h
sk: sub al,30h
 ret
endp
HexToAscii proc
 cmp dl,0ah
 jc sk2
 add dl,07h
sk2: add dl,30h
 ret
endp
Code ends
end Start

【问题讨论】:

  • 有很多(未注释的)代码要阅读,而您还没有解释它有什么问题。如果你能缩小范围,你更有可能获得帮助。将您的代码缩减为minimal reproducible example,并告诉我们它应该做什么以及会发生什么。使用调试器单步执行代码并尽可能多地找出问题是如何出现的。

标签: assembly x86-16 tasm


【解决方案1】:
mov di,1000h

因为在您的 2 hexdigits 输入例程中,用户可以键入的最大值是“FF”(255),您可以在程序的数据部分中保留该大小的缓冲区,而不是仅仅相信偏移地址 1000h 不会与记忆中重要的东西重叠。

Data Segment
 buf db 256 dup (0)
 msg db 0dh,0ah,"Please enter the length of the array: $"
 ...

为了解决获取最小值所在数组元素索引的任务,您可以将DI 中的地址的当前值保存在一个额外的寄存器中,例如SI,并在每次代码出错时更新它在较小的值上:

 ...
 mov di, offset buf
 mov al, [di] 
 mov min, al
 mov si, di    ; Address of the first chosen minimum
chk:
 mov al, [di]
 cmp al, min
 jae a
 mov min, al   ; Smaller than anything before
 mov si, di    ; Remember the address of the newest minimum
a:
 inc di
 loop chk

在这段代码之后,您要查找的索引是通过从找到最小值的地址中减去数组的开头来获得的:

sub si, offset buf  ; The index of the minimum

随着SI 地址的引入,就不再需要单独的min 变量了:

 ...
 mov di, offset buf
 mov si, di    ; Address of the first chosen minimum
chk:
 mov al, [di]
 cmp al, [si]  ; At [si] is the current minimum
 jae a
 mov si, di    ; Remember the address of the newest minimum
a:
 inc di
 dec cx
 jnz chk
 ;;; mov al, [si]    ; The minimum should you need it
 sub si, offset buf  ; The index of the minimum

请注意,我已经删除了较慢的 loop chk 指令,并将其替换为 dec cx jnz chk 对。



Here 是一个非常非常相似的答案,它处理的是最大值而不是最小值......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多