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