与 C++ 相比,程序在汇编语言中给出了错误的计算,我找不到错误。有什么想法吗?
// (2 * c + b + a - 5) / (a / 4 - 1)
#include <iostream>
using namespace std;
void print_of() {
cout << "Overflow error\n";
exit(1);
}
void print_zf() {
cout << "Division by zero error\n";
exit(1);
}
int main() {
long int a, b, c;
long int asm_answer;
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)
mov asm_answer, rax
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;
}
控制台输出示例:
<块引用>输入a、b、c:100 0 20 汇编结果:6 C++ 结果:5 程序以退出代码结束:0
另一个例子:
<块引用>输入a、b、c:0 0 0 汇编结果:-5 C++ 结果:5 程序以退出代码结束:0