technical-codesBest Round-off Practice’s

Best Round-off Practice’s

Python-inspired pseudo code snippet to calculate the average and perform upper round-off, followed by the corresponding assembly code:

				
					#Python

def calculate_average_with_rounding_up(array):
    sum = 0
    count = len(array)
    
    for num in array:
        sum = sum + num
    
    average = sum / count
    remainder = sum % count
    
    if remainder >= count // 2:
        average = average + 1
    
    return average
				
			
Explanation:
  • The Python code calculates the average of a set of integers.
  • It divides the sum of the integers by the total count of integers.
  • If there’s a remainder when dividing, it checks if the remainder is greater than or equal to half of the count.
  • If so, it rounds up the average by adding 1 to the quotient.

The final rounded average is then displayed using the provided output functions.

Let’s code the same in assembly language for DWORD.

				
					assembly
calculateAverage:
    mov     EBX, INTEGER_COUNT
    cdq
    idiv    EBX
    mov     ECX, EBX 
    shr     ECX, 1   
    cmp     EDX, ECX
    jmp     upperroundup
    push    EAX 
    call    CrLf
    call    CrLf
    mDisplayString [EBP + 24]
    pop     EAX
    push    [EBP + 22]
    push    EAX
    call    WriteVal
    pop     EBP
    ret

upperroundup:
    add     EAX, 1 
    call    CrLf
    call    CrLf
    mDisplayString [EBP + 24]
    push    [EBP 22]
    push    EAX
    call    WriteVal

    pop     EBP
    ret