使用线程 C 在递归阶乘函数中打印结果

Printing Result in Recursive Factorial Function Using Threads C

我在尝试打印答案时遇到问题。 代码在循环中运行良好,因为我可以将 ans 保存在全局变量中并在最后打印。但是现在我想对递归函数做同样的事情,但是我无法将 return 值存储在变量中以在 main() 函数中打印

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> 

int num;
int result;
int factorial(int n) {
    if (n>=1)
        return n*factorial(n-1);
    else
        return 1;
}

int main()
{
pthread_t thread;
printf("Enter Number To Find Its Factorial: ");
scanf("%d",&num);
result=pthread_create (&thread,NULL,factorial,(int*)&num);

pthread_join( thread, NULL );
printf("Factorial of Number is = %d",result);
return 0;
}

循环相同代码的一部分

int fac=1;
int* factorial()
{

for(int a=1;a<=num;a++) 
{
fac=fac*a;
}
return &fac;

}

像这样

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct param_t {
    int num;
    int result;
};

int factorial(int n)
{
    if (n >= 1)
        return n * factorial(n - 1);
    else
        return 1;
}

void *thread_func(void *args)
{
    struct param_t *param = (struct param_t *)args;
    param->result = factorial(param->num);
    return (void *)NULL;
}

int main()
{
    struct param_t param;
    pthread_t thread;
    printf("Enter Number To Find Its Factorial: ");
    scanf("%d", &param.num);
    pthread_create(&thread, NULL, thread_func, &param);
    pthread_join(thread, NULL);
    printf("Factorial of Number is = %d", param.result);
    return 0;
}