在 asm8086 中生成斐波那契数列时无限循环

infinite loop while generating Fibonacci series in asm8086

我的代码是根据用户给定的数字生成斐波那契数列的元素.. 问题是每当我输入任何数字时,它都会进入无限循环而不是输出特定的数字。我输入的元素 .. 这是我用来打印斐波那契数列的程序:

displayFib proc
MOV DX, 30h         ; move value 30 hexadecimal to DX, which represents 0
call display
MOV AX, input   
CMP AX, 0        ;if the input is 0 in hexadecimal ASCII value then jump to finish
JE finish_it

mov   ah,9              ; formating - coma
mov   dx,offset msg3
int   21h       

;display the 1st term
MOV DX, 31h         ; move value 31 hexadecimal to DX, which represents 1
call display
CMP input, 1        ;if the input is 1 in hexadecimal ASCII value then jump to finish
JE finish_it

MOV CX, input       ;intializing counter, knowing that first 2 terms were displayed already
SUB CX, 2

repeat:
    mov   ah,9              ; formating - coma
    mov   dx,offset msg3
    int   21h       

    MOV AX, fibn_2        ; calculating the n'th term of a sequence    n = (n-1) + (n-2) 
    ADD AX, fibn_1
    MOV fib, AX
    MOV DX, fib
    MOV saveCount, CX       ;saving the state of the counter as it will be modified in the displayNum
    call displayNum
    ;display the n'th term (current term)
    MOV CX, saveCount       ;restoring state of the counter
    MOV AX, fibn_1        ; n-1 in the next round of a loop will be n-2
    MOV fibn_2, AX
    MOV AX, fib         ;n'th term in the next round will be n-1
    MOV fibn_1, AX
    DEC  CX             ;decrementing counter
    JNZ repeat          ; loop until counter = 0

finish_it:

ret
displayFib endp

谢谢,

MOV CX, input       ;intializing counter, knowing that first 2 terms were displayed already
SUB CX, 2

input 为 2 时会发生什么?无限循环!!!


您的程序失败是因为您没有以正确的方式处理输入!

keyin 例程破坏了 AH 寄存器,但您将 AX 寄存器移动到 num1多变的。通过明确地将 AH 寄存器归零来更正。

call keyin     ;gets user input
SUB AL, 48     ;changes ASCII value into numeric value for further processing

mov ah, 0      <<<<<<< ADD THIS

mov num1 , AX  ;saves user input to variable num1

num2 变量也是如此。


MOV saveCount, CX       ;saving the state of the counter as it will be modified in the displayNum
call displayNum         ;display the n'th term (current term)
MOV CX, saveCount       ;restoring state of the counter

pushing/popping 怎么了?

PUSH CX             ;saving the state of the counter as it will be modified in the displayNum 
call displayNum     ;display the n'th term (current term)
POP CX              ;restoring state of the counter