【问题标题】:Why is program not accurately computing integer SUM?为什么程序不能准确计算整数 SUM?
【发布时间】:2014-02-05 21:16:34
【问题描述】:

我是汇编编程 (x86) 的新手,无法弄清楚我的程序哪里出错了。在我重新显示移动到数组中的值之后,我想显示当前的“SUM”。我认为通过使用“ebx”寄存器,因为除了 Loop2 之外,它在程序中的其他任何地方都没有使用,因此该值不会被覆盖,因此每个“添加”语句都会将新的数组位置值添加到我的“SUM”中.

谁能发现我做错了什么?

INCLUDE Irvine32.inc
COUNT = 3

.data
inputMsg BYTE "Input an integer: ", 0
outputMsg BYTE "Redisplaying the integers: ", 0dh, 0ah, 0
sumMsg BYTE " Sum is now: ", 0
strArray SDWORD COUNT DUP(?)

.code
main PROC
    ; Read Integers from User
    mov ebx, 0
    mov ecx, COUNT
    mov edx, OFFSET inputMsg
    mov esi, OFFSET strArray

L1: call WriteString            ; Display Prompt
    call ReadInt                ; Read input from user
    mov [esi], eax              ; Store value into array
    add esi, TYPE strArray      ; Move to next array position
    loop L1

    call Crlf

    ; Redisplay the integers
    mov edx, OFFSET outputMsg   ; Display 'outputMsg'
    call WriteString
    mov ecx, COUNT
    mov esi, OFFSET strArray

L2: mov ebx, 0                  ; Initialize ebx to 0
    mov eax, [esi]              ; Get integer from array
    call WriteInt               ; Display integer
    mov edx, OFFSET sumMsg      ; Display value of 'sumMsg'
    call WriteString
    ; mov eax, ebx
    add ebx, [esi]

    mov eax, ebx   ; <---- MOVED from above add ebx, [esi]

    call WriteInt
    call Crlf                   
    add esi, TYPE strArray      ; Move to next array position
    loop L2

    exit
main ENDP

END main

【问题讨论】:

    标签: assembly x86 masm irvine32


    【解决方案1】:

    在调用 WriteInt 之前,您需要将 ebx 移动到 eax。在求和循环之前将 ebx 初始化为 0 也是一个好主意。

    【讨论】:

    • 我试着按照你的建议去做(如果我理解正确的话)。现在所有行都作为数组的输出读取,然后是"Sum is now: +0"。我已经编辑了上面的代码以反映更改。还有什么想法吗?
    • 你把mov eax, ebx 放错地方了。把它放在call WriteInt之前
    • 我将mov eax, ebx 移动到add ebx, [esi]call WriteInt 之上。现在输出是:+1 Sum is now: +1 +2 Sum is now: +2 +3 Sum is now: +3我还缺少什么?
    • mov ebx, 0 应该在 L2 之前,否则每次迭代都会将总和重置为 0。
    • 就是这样,谢谢! :)
    【解决方案2】:

    在调用最后一个 WriteInt 之前,您可能必须“mov eax, ebx”。

    【讨论】:

    • 我已按照您和 ooga 的建议编辑了我的代码。输出现在读取为数组值,后跟"Sum is now: +0" 以及我修改后的代码。还有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2013-12-12
    • 2015-10-28
    相关资源
    最近更新 更多