我编写了一个程序来查找两个值的GCD。因此,我建立了用于打印步骤的循环(这是必需的)。问题是,我没有打印出最终结果,我认为这是因为即使我有返回语句,我的循环也不会返回任何东西。任何人都可以发现我的问题,还是必须添加更多的退货声明以“突破” gcd方法以回到主方法? (它不是要编辑主方法或打印功能,而仅是gcd方法)
代码:
; main-Method
BIPUSH 0 // OBJREF
INVOKEVIRTUAL main
HALT
; main-Method
main 1 2 // Arguments 0 = OBJREF, loc. variables 1 = a, 2 = b
BIPUSH 15 // a
ISTORE 1
BIPUSH 50 // b
ISTORE 2
BIPUSH 0
ILOAD 1
ILOAD 2
INVOKEVIRTUAL gcd
; print
ILOAD 2
ILOAD 1
SPRINT "Result: gcd("
IPRINT
SPRINT ","
IPRINT
SPRINT ") = "
IPRINT
SPRINT "\n"
IRETURN
; gcd(a, b)
; 2 Arguments (#1=a, #2=b), no local variables
gcd 3 0
;;;
# Call of the method;
SPRINT "Call gcd("
ILOAD 1
IPRINT
SPRINT ","
ILOAD 2
IPRINT
SPRINT ")\n"
# if(a == b);
:IF1
POP
POP
POP
ILOAD 1
ILOAD 2
IF_ICMPEQ END1
GOTO IF2
# if(a > b);
:IF2
ILOAD 1
ILOAD 2
ISUB
IFLT END3
GOTO IF3
# if(a < b);
:IF3
ILOAD 2
ILOAD 1
ISUB
IFLT END2
# return a;
:END1
BIPUSH 0
ISTORE 0
ILOAD 1
ISTORE 0
POP
POP
POP
POP
GOTO RECURSIVEPRINT
# return gcd(a-b, b);
:END2
ILOAD 1
ILOAD 2
ISUB
ISTORE 1
ILOAD 1
ILOAD 2
GOTO METHOD
# return gcd(b-a, a);
:END3
ILOAD 2
ILOAD 1
ISUB
ISTORE 2
SWAP
ILOAD 1
ILOAD 2
GOTO METHOD
:METHOD
INVOKEVIRTUAL gcd
ISTORE 0
GOTO OUT
:OUT
IRETURN
:END
ILOAD 0
IRETURN
:RECURSIVEPRINT
ILOAD 1
IFEQ DELETESTACK
ILOAD 2
IFEQ DELETESTACK
SPRINT "Recursive gcd("
ILOAD 1
IPRINT
SPRINT ","
ILOAD 2
IPRINT
SPRINT ") = "
ILOAD 0
IPRINT
SPRINT "\n"
ISTORE 2
ISTORE 1
GOTO RECURSIVEPRINT
:DELETESTACK
POP
POP
ISTORE 2
ISTORE 1
GOTO LASTRECURSIVE
:LASTRECURSIVE
SPRINT "Recursive gcd("
ILOAD 1
IPRINT
SPRINT ","
ILOAD 2
IPRINT
SPRINT ") = "
ILOAD 0
IPRINT
SPRINT "\n"
IRETURN
GOTO END
预期结果:
Call gcd(15,50)
Call gcd(35,15)
Call gcd(20,15)
Call gcd(5,15)
Call gcd(10,5)
Call gcd(5,5)
Recursive gcd(5,5) = 5
Recursive gcd(10,5) = 5
Recursive gcd(5,15) = 5
Recursive gcd(20,15) = 5
Recursive gcd(35,15) = 5
Recursive gcd(15,50) = 5
Result: gcd(15,50) = 5
实际结果:
Call gcd(15,50)
Call gcd(35,15)
Call gcd(20,15)
Call gcd(5,15)
Call gcd(10,5)
Call gcd(5,5)
Recursive gcd(5,5) = 5
Recursive gcd(10,5) = 5
Recursive gcd(5,15) = 5
Recursive gcd(20,15) = 5
Recursive gcd(35,15) = 5
Recursive gcd(15,50) = 5