使用用户定义的函数在 c 中给出垃圾值的数字的阶乘

Factorial of a number using user defined function giving garbage value in c

我试图构建一个程序来使用用户定义的函数计算阶乘,但它给出了一个垃圾值这个程序是 c-cat 准备的作业

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int accept_num();             // Function call
int fact();                   // Function call
void display_num();           // Function call
int main()
{
    int num;

    num = fact();        //calling factorial

    display_num(num);    //calling printf

}
    //take input
    int accept_num()
{
     int n;
     printf("Enter number: ");
     scanf("%d",&n);
     return n;
 }
    //calculate factorial
 int fact()
{
    int i,num1;
    unsigned long long factr=1;

    num1 = accept_num();

    for(i=1; i<=num1; i++)
    {
        factr *= i;
    }
    return factr;
}

void display_num(int num2)
{
    printf("Answer = %llu",num2);
}

类型不匹配通常会导致垃圾值。计算阶乘后,您将其存储为 int 类型,并在 display_num() 函数中打印 unsigned long long int,它保留的位数比 int 多。此外,如果您使用 int i,在 int.

的限制后循环迭代后,将导致阶乘的假值

下面是细化后的代码,将每个int替换为unsigned long long int

#include<stdio.h>
#include<stdlib.h>
unsigned long long int accept_num();             // Function call
unsigned long long int fact();                   // Function call
void display_num();           // Function call
int main()
{
    //changed the datatype of num
    unsigned long long int num;

    num = fact();        //calling factorial

    display_num(num);    //calling printf

}
    //take input
   unsigned long long int accept_num()
{
    //changed datatype of n
     unsigned long long int n;
     printf("Enter number: ");
     scanf("%llu",&n);
     return n;
 }
    //calculate factorial
 unsigned long long int fact()
{
    unsigned long long int i;

    //changed datatype of num1
    unsigned long long int num1;
    unsigned long long int factr=1;

    num1 = accept_num();

    for(i=1; i<=num1; i++)
    {
        factr *= i;
    }
    return factr;
}

//changed datatype of argument num2
void display_num(unsigned long long int num2)
{
    printf("Answer = %llu",num2);
}

另外,还有更多的冗余变量可以减少。参考这段代码:

#include<stdio.h>
long int multiplyNumbers(int n);

int main() {
    int inputNumber;
    printf("Enter a positive integer: ");
    scanf("%d",&inputNumber);
    printf("Factorial of %d = %ld", inputNumber, multiplyNumbers(inputNumber));
    return 0;
}

//calculate factorial using recursion
long int multiplyNumbers(int n) {
    if (n>=1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}