[英]A variation of fibonacci assembly x86, have to call it from a c++ main method, kind of lost at few parts
這是斐波那契代碼,
unsigned int fib(unsigned int n)
{
if (n==1 || n ==2)
return 1;
else
return fib(n-2) + fib(n-1);
}
但是對於我的代碼,我必須將公式更改為一個新的公式,即f(n-2)/ 2 + f(n-1)* 2,因此序列為1、2、4、9、20、44 98、218
我需要在匯編中編寫一個稱為Mobonacci的遞歸函數以按順序計算第n個數字,還要在c ++中編寫一個主函數,該函數讀取一個正數n,然后用參數n校准mobonacci匯編函數,然后打印結果
所以我有點困惑,我是否像下面那樣在匯編中編寫函數,然后編寫一個c ++函數來調用它? 伙計們如何將我的代碼從斐波那契更改為新公式? 這是我的代碼,我需要更改什么,還需要創建新部分以使代碼讀取輸入? 我的代碼也太短了嗎? 我需要添加其他東西嗎?
.code
main PROC
mov ecx,0
push 4 ; calculate the nth fib
call Fib ; calculate fib (eax)
call WriteDec
call Crlf
exit
main ENDP
Fib PROC
add ecx,1
push ebp
mov ebp,esp
mov eax,[ebp+8] ; get n
cmp eax,2 ; n == 2?
je exception2
cmp eax,1 ; n == 1?
je exception2
dec eax
push eax ; Fib(n-1)
call fib
add eax,
jmp Quit
Exception2:
dec eax
Quit:
pop ebp ; return EAX
ret 4 ; clean up stack
Fib ENDP
END main
取決於您嘗試將asm代碼插入c ++代碼的位置...對於gcc / linux,您可以執行以下操作:
//Simple example:
void *frame; /* Frame pointer */
__asm__ ("mov %%ebp,%0":"=r"(frame));
//Complicated example:
int foo(void) {
int joe=1234, fred;
__asm__(
" mov %1,%%eax\n"
" add $2,%%eax\n"
" mov %%eax,%0\n"
:"=r" (fred) /* %0: Out */
:"r" (joe) /* %1: In */
:"%eax" /* Overwrite */
);
return fred;
}
重要的是要了解如何在cpp中使用asm函數。 您可以在這里找到有關此主題的一些有用的信息: https : //www.cs.uaf.edu/2011/fall/cs301/lecture/10_12_asm_c.html
關於問題的第二部分。 要成倍增加,可以使用命令“ mul ”並進行除法“ div ”。 因此,如果要執行f(n-1)* 2,則必須在“ call fib ”之后注冊%eax並使用mul。
只需在這里看看: http : //www.tutorialspoint.com/assembly_programming/assembly_arithmetic_instructions.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.