如何显示在 tasm 程序中找到的元素的索引

how to show the index of element found in tasm program

如何显示找到的元素的索引号? 我已经找到数组中的最大元素,现在我想打印我找到的元素的索引如何继续?

我想根据以下逻辑找到我在数组中找到的最大数字的元素?

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 maximum is: $"
 len db ?
 max 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 max,al

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

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

 mov bl,max
 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

你可以找到一个非常非常相似的答案here多么奇怪,一个处理最大值而另一个处理最小值...



mov di,1000h

因为在您的 2 个十六进制数字输入例程中,用户可以键入的最大值是“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 max, al
 mov si, di    ; Address of the first chosen maximum
chk:
 mov al, [di]
 cmp al, max
 jbe a
 mov max, al   ; Bigger than anything before
 mov si, di    ; Remember the address of the newest maximum
a:
 inc di
 loop chk

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

sub si, offset buf  ; The index of the maximum

随着 SI 地址的引入,不再需要单独的 max 变量的机会来了:

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

请注意,我删除了速度较慢的 loop chk 指令,并将其替换为 dec cx jnz chk.