Par*_*wat 0 c variables factorial
所以我正在编写一个程序来打印 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)
因为当您增加变量时a,for 循环条件会发生变化。您必须i小于a,但递增a将导致条件始终为真。您必须将值保存在另一个变量中,如下所示:
#include <stdio.h>
int main(void)
{
int a, i;
printf("Enter the number = ");
scanf("%d", &a);
int result = a;
for(i=1; i<a; i++){
result = result*i;
}
printf("The factorial of the given number is = %d \n", result);
}
Run Code Online (Sandbox Code Playgroud)