MASM将数组中的元素总和相加

时间:2015-11-04 17:57:45

标签: arrays assembly sum masm irvine32

我只是想编写一个简单的程序,它接受来自用户的x个整数,让用户输入它们,然后使用子程序计算数组的总和并打印出总和。

我想将EAX中的数组地址和数组元素的数量传递给EBX。

;Lab 4

title Template Lab4 Adder

INCLUDE Irvine32.inc ;32bit assembler

.data
theansweris DWORD ?
welcometoadder BYTE "Welcome to adder",0dh,0ah,0
howmanynumbers BYTE "How many numbers would you like to add?:",0dh,0ah,0
enteranumber BYTE "Enter a Number:",0dh,0ah,0
youentered BYTE "You entered:",0dh,0ah,0
thesumis BYTE "The sum of the numbers is:",0dh,0ah,0
space BYTE " ",0dh,0ah,0
readStr    DB  50 DUP(?) ;allocates 50 BYTES WITH ?
var1 DWORD ?
testz DWORD 0
sum         BYTE    11 DUP(?), " is the sum.", 0dh, 0ah
numArray    DWORD   ?
numElts     DWORD   100
num         DWORD   ?
resultLbl   BYTE    "Results", 0

.code
main PROC
    call Clrscr
    mov edx, OFFSET welcometoadder
    call WriteString
    ;mov     ecx, 100                   ; loop count (size of array)
    ;lea     ebx, numElts               ; get address of the array
    mov edx, OFFSET howmanynumbers
    call WriteString

    mov edx,OFFSET enteranumber
    call WriteString
    call ReadInt
    mov edx,OFFSET youentered
    call WriteString
    mov ebx,eax
    mov edx,ebx
    call WriteInt
    mov edx, OFFSET space
    call WriteString
    ;mov ebx,edx
    mov ecx,ebx
    lea ebx,NumElts

LOOP1:
        mov edx, OFFSET enteranumber
        call WriteString
        mov edx, OFFSET space
        call WriteString
        call ReadInt
        mov     [ebx], eax                  ; store in the array            
        add     ebx, 4                      ; get address of next array elt
        cmp ecx,0
        je LOOP2
        loop    LOOP1                       ; repeat nbrElts times
LOOP2:
call DumpRegs
;mov eax,[ebx]                  ;get the num
;add edx,eax                    ;increase the sum
;add ebx,4                      ;next array element
;loop LOOP2

;    CALL ADDER

;ADDER PROC
;    add bx, cx
;    add bx, cx
;    add ax, bx
    ;mov edx, OFFSET thesumis
    ;call WriteString
;    RET
;ADDER ENDP

    exit
    main ENDP

END main

3 个答案:

答案 0 :(得分:1)

您的程序没有预留任何内存来存储阵列!
你写的只是:

numElts DWORD   100

mov     ecx, ebx
lea     ebx, NumElts
LOOP1:

将定义更改为:

numElts DWORD   100 dup(?)

附加。在 LOOP1 中,ECX的额外测试是无用的!

cmp     ecx, 0      <<<< remove
je      LOOP2       <<<< remove
loop    LOOP1
LOOP2:

答案 1 :(得分:0)

看起来您可能需要在加法器子过程中使用某种堆栈操作和循环。 ECX是循环计数器,所以第一部分应该工作。在调用子过程之前,您需要重置循环计数器。

答案 2 :(得分:-5)

ADDER PROC
add eax,[ebx]
像我猜的那样