我正试图用汇编语言四舍五入到我最近的整数,我一直在试图解决它。例如,如果我执行除法函数137/6,如何将结果舍入到最接近的整数?
答案 0 :(得分:2)
对于正值,在除法之前将分母的一半加到分子上。我将负面价值的更复杂情况留给你。
mov ecx, [denominator] ; divisor
mov eax, ecx ; copy to numerator register
shr eax, 1 ; half divisor
add eax, [numerator] ; add to numerator
div ecx ; (numerator + denominator/2) / denominator
答案 1 :(得分:1)
“Round half towards positive infinity”表示正数(评论中的解释):
xor edx, edx ; Clear EDX for division
mov eax, [numerator] ; Dividend stored in the data section (eg. dd 137)
mov ecx, [denominator] ; Divisor stored in the data section (eg. dd 6)
div ecx ; EDX:EAX / ECX = EAX remainder EDX
shl edx, 1 ; EDX *= 2
cmp edx, ecx ; Fraction part < 0.5 (remainder*2 < divisor) ?
jb .done ; Yes: skip rounding
add eax, 1 ; No: round half up (http://en.wikipedia.org/wiki/Rounding#Round_half_up)
.done: ; EAX = rounded result of division