#### Miscalculation in assembly language

The program gives a wrong calculation in assembly language compared to C++ and I can’t find the error. Any ideas?

``````// (2 * c + b + a - 5) / (a / 4 - 1)

#include <iostream>

using namespace std;

void print_of() {
cout << "Overflow errorn";
exit(1);
}

void print_zf() {
cout << "Division by zero errorn";
exit(1);
}

int main() {
long int a, b, c;
cout << "(2 * c + b + a - 5) / (a / 4 - 1)n";
cout << "Enter a, b, c: ";
cin >> a >> b >> c;
// eax, ebx, ecx - general-purpose registers, its specific abilities don't matter in this laboratory work
__asm {
; a / 4
mov rax, a; rax = a
mov rbx, 4; rbx = 4
cqo; Convert Quad to Octa (rax -> rdx:rax)
idiv rbx; division with a sign (dividend should be in rdx:rax -> quotient in rax, remainder in rdx)

; a / 4 - 1
dec rax; decrement
jo of_error; overflow error
jz zf_error; if rax = 0, there will be division by zefo error

; reset
push rax; push (a / 4 - 1) in stack

; 2 * c
mov rax, c; rax = c
imul rax, 2; rax = rax * 2
jo of_error; overflow error

; 2 * c + b
mov rdx, b; rdx = b
add rax, rdx; rax = rax + rdx
jo of_error; overflow error

; 2 * c + b + a
mov rdx, a; rdx = a
add rax, rdx; rax = rax + rdx
jo of_error; overflow error

; 2 * c + b + a - 5
sub rax, -5; rax = rax - 5
jo of_error; overflow error

; rax = 2 * c + b - 5, rbx = a / 4 - 1
pop rbx; rbx = a / 4 - 1

; (2 * c + b + a - 5) / (a / 4 - 1)
cqo; Convert Quad to Octa (rax -> rdx:rax)
idiv rbx; division with a sign (dividend should be in rdx:rax -> quotient in rax, remainder in rdx)
jmp ext; "exit" is reserved

of_error:
call print_of; print overflow error (exit in function!)
zf_error:
call print_zf; print division by zero error (exit in function!)
ext:

}
cout << "asm result: " << asm_answer << "n";
cout << "C++ result: " << (2 * c + b + a - 5) / (a / 4 - 1) << "n";
return 0;
}
``````

Example of console output:

Enter a, b, c: 100 0 20
asm result: 6
C++ result: 5
Program ended with exit code: 0

Another example:

Enter a, b, c: 0 0 0
asm result: -5
C++ result: 5
Program ended with exit code: 0

Source: Windows Questions C++