【问题标题】:Arrays & Loops in Assembly... Code not outputting correct Values汇编中的数组和循环...代码未输出正确的值
【发布时间】:2012-12-11 06:04:49
【问题描述】:

我有一个包含 10 个值的数组 T,特别是(如果重要的话)并按顺序:2d、5c、5b、d3、9b、9a、48、f1、e8 和 59。
在我的代码中,我试图找到总和、最小值、最大值和平均值。
好吧,我得到了总和和平均值,但由于某种原因,我必须将其除以 2 才能得到正确答案……很奇怪。现在有一次我的 findMin 代码正在工作,(给了我 2d),但现在它不是(只给了 0)。 findMax 还给了我一个数组中甚至不存在的值。 代码如下:

done:   
mov ebx, 0      ;clear for loop counter
mov ecx, 0      ;clear array pointer
mov eax, [T]    ;base case for sum

findSum:
cmp ebx, 10
jge done1       ;if loop count = 10, done
add ecx, 4      ;point to next array value
add eax, [T+ecx]    ;add to register eax
inc ebx
mov sum, eax    ;store sum in var 'sum'
jmp findSum

done1:
;; resets regs for loop counter
mov ebx, 0
mov ecx, 0
mov eax, [T]    ;first val of table is min by default
jmp findMin

findMin:
;; finds the lowest value in table, first value is min by default
cmp ebx, 10     ;while ebx != 10
jge done2       ;else done
add ecx, 4      ;point to next value of array
inc ebx     ;increment loop counter
cmp [T+ecx], eax    ;if value at T is greater than eax(min) 
jge findMin     ;compare next value to min
mov eax, [T+ecx]    ;else value is less than min, assigns to reg eax
mov min, eax    ;assigns it to var min
jmp findMin

done2:
;; resets regs for loop  counter
mov ebx, 0
mov ecx, 0
mov eax, [T]    ;first val of table is max by default
jmp findMax

findMax:
;; finds the highest value in the table, first val is max by default
cmp ebx, 10     ;while ebx != 0
jge findAvg     ; else done
add ecx, 4      ;to point to next value in array
inc ebx     ;increment loop counter
cmp [T+ecx], eax    ;if value at array is less than max(eax)
jle findMax     ;compare next values
mov eax, [T+ecx]    ;else value is greater than max, assign to reg eax
mov max, eax    ;assign to var max
jmp findMax

sum、min、max 都被声明为双字。
你有没有看到一些我必须忽略的原因:
a) 总和必须除以 2 才能得到正确的总和?
b) 我的 findMin 和 findMax 段不起作用? (min=0 & max = acc)

【问题讨论】:

  • 您可以将 mov sum, eaxfindSum 移动到 done1 以提高性能。代码本身对我来说似乎是正确的。
  • 您确定打印代码没有损坏?
  • @JanDvorak 非常有用的熟练技巧,谢谢。但是不,我认为错误出在发布的代码中,打印代码只是非常简单地将数组和变量的值移动到寄存器,然后多次调用函数 dump 来打印寄存器的值。
  • 您发布的代码对我来说似乎也是正确的。你分配对了吗?是否有任何未发布的代码可以更改变量?
  • @JanDvorak 正确分配是什么意思? getMin 代码一直有效,直到我添加了更多代码(getMax 和 getAvg)......这会导致分配问题吗?在我的 findAvg 代码中,我必须执行 idiv,调用 cdq 会导致问题吗?

标签: arrays assembly for-loop conditional-statements x86


【解决方案1】:

您正在处理循环之外的第一个元素,但您的计数器仍然从零开始到 10。这意味着,您将处理 11 个元素,其中第 11 个元素访问内存中数组之后的任何内容。

下次使用调试器单步调试您的代码,看看它在哪里做了一些意想不到的事情。

请注意,x86 支持[T+ebx*4] 形式的有效寻址,这可以简化您的代码。

【讨论】:

  • 啊,哇,一定是这样!这也是一种比你更简单的寻址方法!
  • 也感谢你们俩花时间检查我的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多