x86汇编简易计算器仅减法结果正确,其他运算符计算异常求助
x86汇编简易计算器:仅减法正确,其他运算结果错误的修复方案
你的代码核心问题是读取数字时未清除AX寄存器的高8位(AH),导致num1和num2存储了包含垃圾值的16位数据,而非预期的0-9单数字:
- DOS中断
int 21h的1号功能(键盘输入)仅修改AL寄存器,AH保留了之前调用其他中断时的值(比如09h、2h) - 你直接将整个
AX存入num1和num2(均为dw类型,16位),导致这两个变量的高8位是随机垃圾值 - 减法运算偶然正确是因为两次输入数字时
AH的值可能相同,相减后高字节抵消,低字节结果正确;但加减乘除的其他运算会被高字节的垃圾值破坏结果
修复后的完整代码(修改处已标注):
IDEAL MODEL small STACK 100h DATASEG num1 dw ? num2 dw ? operator db ? result dw ? prompt1 db "Enter first number: $" prompt2 db "Enter operator (+, -, *, /): $" prompt3 db "Enter second number (second number should be smaller than first): $" outputMsg db "Result: $" string db 10 dup('$') debugMsg db "Operator value: $" CODESEG start: mov ax, @data mov ds, ax mov dl, 0ah mov ah, 2h int 21h ; ask for first number mov ah, 09h mov dx, offset prompt1 int 21h ; read first number mov ah, 1h int 21h sub al, '0' xor ah, ah ; 修复:清空AH,确保AX仅包含数字的16位值(000X) mov [num1], ax mov dl, 0ah mov ah, 2h int 21h ; ask for operator mov ah, 09h mov dx, offset prompt2 int 21h ; read operator mov ah, 1h int 21h mov [operator], al mov dl, 0ah mov ah, 2h int 21h ;print operator value for debugging mov ah, 09h mov dx, offset debugMsg int 21h mov dl, [operator] mov ah, 2h int 21h mov dl, 0ah mov ah, 2h int 21h ; ask for second number mov ah, 09h mov dx, offset prompt3 int 21h ;read second number mov ah, 1h int 21h sub al, '0' xor ah, ah ; 修复:清空AH,确保AX仅包含数字的16位值(000X) mov [num2], ax mov dl, 0ah mov ah, 2h int 21h ; do calculation cmp [operator], '+' je ADDITION cmp [operator], '-' je SUBTRACTION cmp [operator], '*' je MULTIPLICATION cmp [operator], '/' je DIVISION jmp EXIT ADDITION: mov ax, [num1] add ax, [num2] mov [result], ax jmp OUTPUT SUBTRACTION: mov ax, [num1] sub ax, [num2] mov [result], ax jmp OUTPUT MULTIPLICATION: mov ax, [num1] mul [num2] mov [result], ax jmp OUTPUT DIVISION: mov ax, [num1] mov dx, 0 div [num2] mov [result], ax jmp OUTPUT OUTPUT: ;show result mov ah, 09h mov dx, offset outputMsg int 21h mov bx, 10 mov cx, 0 mov ax, [result] l1: mov dx, 0 div bx add dl, '0' push dx inc cx cmp ax, 0 jne l1 mov bx, offset string l2: pop dx mov [bx], dl inc bx loop l2 mov ah, 09h mov dx, offset string int 21h mov dl, 0ah mov ah, 2h int 21h exit: mov ax, 4c00h int 21h END start
额外优化建议:
- 可将
num1和num2改为db类型(8位),减少内存占用,同时避免高字节问题,读取时直接存al即可 - 除法运算建议添加除数为0的判断,防止程序崩溃
- 输入提示里的"second number should be smaller than first"仅适用于减法,除法需要除数不为0,可调整提示文本
内容的提问来源于stack exchange,提问作者Idan
相关产品推荐
相关产品推荐

