小编Par*_*wat的帖子

C 中数字的阶乘

所以我正在编写一个程序来打印 C 中数字的阶乘。我的代码 -

#include <stdio.h>
int main(void)
{
    int a,i ;
    printf("Enter the number = ");
    scanf("%d", &a);

    for(i=1; i<a; i++)
    {
        a = a*i;
    }
    printf("The factorial of the given number is = %d\n",a);
}
Run Code Online (Sandbox Code Playgroud)

现在这个程序正在打印一些垃圾值。我问了一些朋友,他们说为阶乘添加另一个变量,并使用该阶乘变量的循环,但他们都不知道为什么这段代码是错误的。

我的问题是为什么这段代码是错误的?这个 For 循环在这里做什么?为什么它不打印数字的阶乘,而是打印一些垃圾值?

预期产出-

Enter the number = 5
The factorial of the given number is = 120
Run Code Online (Sandbox Code Playgroud)

我得到的输出是-

Enter the number = 5
The factorial of the given number is = -1899959296
Run Code Online (Sandbox Code Playgroud)

c variables factorial

0
推荐指数
1
解决办法
641
查看次数

标签 统计

c ×1

factorial ×1

variables ×1