【汇编】第一个汇编程序 输出数组最大值以及最大值下标

include irvine32.inc
;输出数组最大值以及最大值下标
.data
arr dword 100 dup(?);定义一个最大容量为100的数组
cnt dword ?;数组长度待定
.code
start:
        call readint
        mov  cnt,eax;获取数组长度
        call inputarr;读入数组
        call findmax;找到最大值,返回值eax=max esi=address
        call writeint;输出eax,即最大值
        call crlf;回车
        mov eax,esi
        call writeint;输出最大值下标
        call crlf
final:  exit
end start

inputarr proc
mov ebx,0;ebx记录当前下标
again1:
        cmp ebx,cnt
        jz final1;相等时退出循环
        call readint;不相等时读入
        mov arr[ebx*4],eax
        inc ebx
        jmp again1
final1:
        ret
inputarr endp

findmax proc
mov ebx,0;ebx记录下标
mov eax,arr[0];暂时假设第0个元素最大
mov esi,0
again2:
        cmp ebx,cnt
        jz final2
        cmp eax,arr[ebx*4]
        ja next
        mov eax,arr[ebx*4]
        mov esi,ebx
next:
        inc ebx
        jmp again2
final2:
        ret
findmax endp

小问题:
全局变量arr和函数的耦合太严重了,下一个程序将避免出现这样的问题

改进版:
函数封装良好,只使用了寄存器,未出现全局变量

;内存中三个数组,分别求三个数组的最大值以及下标
;pro:任意个数数组
include irvine32.inc
.data
arr dword 100 dup(?)
cnt_arr dword ?
cnt_item dword ?
.code
main proc
    call readint
    mov cnt_arr,eax
again1:
    cmp cnt_arr,0
    jz final
    call readint
    mov ecx,eax
    mov edx,offset arr
    call readarr
    call findmax
    sub cnt_arr,1
    jmp again1
    final:
main endp

readarr proc
mov ebx,0
again2:
    cmp ebx,ecx
    jz final2
    call readint
    mov [edx+ebx*4],eax
    inc ebx
    jmp again2
final2:
    ret
readarr endp

findmax proc
mov ebx,0
mov eax,[edx]
mov esi,0
again3:
        cmp ebx,ecx
        jz final3
        cmp eax,[edx+ebx*4]
        ja next
        mov eax,[edx+ebx*4]
        mov esi,ebx
next:
        inc ebx
        jmp again3
final3:
        call writeint
        call crlf
        mov eax,esi
        call writeint
        call crlf
        ret
findmax endp

end main
posted @ 2022-03-10 23:47  Exungsh💫  阅读(470)  评论(0编辑  收藏  举报