首页 > 解决方案 > 在用汇编编写的程序中添加两个数字时得到意外结果

问题描述

我在汇编中编写了一个程序,要求用户一个一个地输入两个数字,然后将两个数字相加后在控制台上打印结果。在 x86 架构下编译程序后,当我运行程序时,程序会询问两个数字。但问题是,如果我一个接一个地输入两个数字,并且连续数字的结果大于9,就会在屏幕上产生意想不到的结果。下面我提到了步骤,我经历了,并面临问题。

  1. 下面是一个简单的程序,用汇编代码编写:
; firstProgram.asm

section .data
msg1 db "please enter the first number: ", 0xA,0xD
len1 equ $- msg1
msg2 db "please enter the second number: ", 0xA,0xD
len2 equ $- msg2
msg3 db "the result is: "
len3 equ $- msg3

section .bss
num1 resb 2
num2 resb 2
result resb 2


section .code
global _start

_start:
; ask the user to enter the first number 
mov eax, 4
mov ebx, 1
mov ecx, msg1
mov edx, len1
int 0x80

; store the number in num1 variable 
mov eax, 3
mov ebx, 0
mov ecx, num1
mov edx, 2
int 0x80

; print the first number
mov eax, 4
mov ebx, 1
mov ecx, num1
mov edx, 2
int 0x80


; ask the user to enter the second number 
mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, len2
int 0x80

; store the number, enter by the user in num2 variable 
mov eax, 3
mov ebx, 0
mov ecx, num2
mov edx, 2
int 0x80

; print the second number, enter by user 
mov eax, 4
mov ebx, 1
mov ecx, num2
mov edx, 2
int 0x80

; move the two numbers to eax and ebx register 
; and subtract zero to convert it into decimal
mov eax, [num1]
sub eax, '0'

mov ebx, [num2]
sub ebx, '0'

;add two numbers 
; and add zero to convert back into ascii 
add eax, ebx
add eax, '0'

; store the number in result variable 
mov [result], eax

; print a message to the user before printing the result
mov eax, 4
mov ebx, 1
mov ecx, msg3
mov edx, len3
int 0x80

; now print the result 
mov eax, 4
mov ebx, 1
mov ecx, result
mov edx, 2
int 0x80

; exit the program
mov eax, 1
mov ebx, 0
int 0x80
  1. 写完代码后,我在终端上编译并执行如下:
nasm -f firstProgram.asm -o firstProgram.o
ld -m elf_i386 -s -o first firstProgram.o
./first
<blockquote>
please enter the first number: 

5
please enter the second number: 

3
the result is: 8please enter the first number: 

6
please enter the second number: 

4
the result is: :please enter the first number: 

4
please enter the second number: 

67the result is: :Aplease enter the first number: 

25please enter the second number: 

 the result is: 5
</blockquote>

谁能举例说明原因?

标签: assemblyx86

解决方案


如果在打印输出后清理寄存器怎么办?

你可以做一个xor寄存器,这将清除你从最后一个总和中存储的所有垃圾,即:

; Clean registers.
xor eax, eax 
xor ebx, ebx
xor edx, edx
xor ecx, ecx

推荐阅读