【汇编程序】实现求n阶乘子程序(递归)

程序需求:编写一个求n!的子程序,利用它求1!+2! +3! +4! +5! +6! +7! +8! 的和并输出。
编程思路:先写出C语言实现,再写汇编实现,汇编中使用栈来传递参数。

开发环境

Win10 + VS2017

C语言代码实现如下:

#include 

int sum = 0;
int recursion(int n)
{
	if (n == 0)
		return 1;
	return n * recursion(n - 1);
}
int main()
{
	for (int i = 1; i <= 8; i++)
	{
		int tmp = recursion(i);
		printf("%d! == %d\n", i, tmp);
		sum = sum + tmp;
	}
	printf("sum is %d\n", sum);
	return 0;
}

汇编语言代码实现如下:

INCLUDELIB kernel32.lib
INCLUDELIB ucrt.lib
INCLUDELIB legacy_stdio_definitions.lib
 
.386
.model flat,stdcall
 
ExitProcess PROTO,
dwExitCode:DWORD
 
printf    PROTO C : dword,:vararg
scanf    PROTO C : dword,:vararg
 
.data
sum dword 0
msg1 byte '%d! == %d',10,0
msg2 byte 'sum is %d',10,0
.code

main Proc
	mov esi,1
	jmp testing
body:
	push esi
	call recursion

	pushad
	invoke printf,offset msg1,esi,eax
	popad

	mov ebx,dword ptr sum
	add eax,ebx
	mov dword ptr sum,eax
	
	inc esi
testing:
	cmp esi,8
	jle body

	invoke printf,offset msg2,eax

	push 0h
	call ExitProcess
main endp

recursion proc
	push ebp
	mov ebp,esp
	push ebx
	cmp dword ptr [ebp+8],0
	jne next
	mov eax,1
	jmp over
next:
	mov ebx,dword ptr [ebp+8]
	dec ebx
	push ebx
	call recursion
	inc ebx
	imul eax,ebx
over:
	pop ebx
	pop ebp
	ret 4
recursion endp

end main

编译运行后结果如下:

【汇编程序】实现求n阶乘子程序(递归)_第1张图片

你可能感兴趣的:(【汇编程序】,汇编程序,汇编子程序,递归,阶乘)