使用 C 和 NASM 进行数字的递归阶乘

问题描述 投票:0回答:1

我正在尝试查找用户输入数字的阶乘,并显示它。

我面临的问题是,无论输入是什么,输出总是1。

输入输出部分是通过C语言完成的,如下代码,

#include <stdio.h>

extern int factorial(int n);

int main() {
    int n, res;

    printf("Enter a number: ");
    scanf("%d", &n);

    res = factorial(n);

    printf("Factorial of %d is: %d\n", n, res);
    return 0;
}

包含阶乘代码逻辑的 NASM 代码如下,

section .text
    global factorial

factorial:
    ; Input:  ecx

    ; Base case
    cmp ecx, 1
    jbe .base_case    

    ; Recursive case
    push ecx ;save n in stack

    ; Recurcive call with n-1
    dec ecx
    call factorial

    pop ecx ;pop from stack

    imul eax, ecx

    ret

.base_case:
    mov eax,1
    ret

为了更好地理解代码,我添加了注释。

我用来编译它的命令如下

nasm -f elf RecurciveFactorial.asm && gcc -m32 -o RecurciveFactorial RecurciveFactorial.c RecurciveFactorial.o && ./RecurciveFactorial

我尝试将

jbe
更改为
jle
并更改
imul
的顺序,即,
imul eax,ecx
imul ecx,eax
,并且还用值 1 初始化
eax
寄存器,但这也不起作用。

我也收到此警告 -

这是我第一次做C和NASM的链接。

factorial
在C代码中被调用,我也测试了该部分。

我们将非常感谢您的帮助,并告诉我该警告是否重要或可以忽略。

c assembly nasm factorial
1个回答
0
投票

第一个函数arg是通过rdi寄存器传递的,你很有可能在ecx中的基值处有0,并且跳转到base_case,在那里你将1移动到你recv的rax寄存器上。

You can check here the usage of all register

© www.soinside.com 2019 - 2024. All rights reserved.