The method of calculating n factorial in C language: first create a script file and write the header file; then define an "i" variable for looping and the variable "n"; then use "sum" to save it Result; finally run the script file to achieve n factorial.
The calculation of factorial in C language is actually the accumulation from 1 to n, so we can use a for loop to calculate the product sequentially from 1 to n Implementing the calculation of factorial
In the C language, we often encounter the problem of finding the factorial of a number. For those who have just learned the C language, finding the factorial is a must. Next, in the article, I will share with you how to implement factorial calculation through C language code. It has certain reference value and I hope it will be helpful to everyone.
[Recommended course: C Language Tutorial】
(1) Write the header file, which is the code that every C language program must write
#include<stdio.h>
(2) We can use a for loop to achieve this. First define an i variable for looping, and a variable n to find its factorial and sum to save the result. As shown below
int main() { int n,i,s=1,sum=0; printf("请输入所求的阶乘数:"); scanf("%d",&n); for(i=1;i<=n;i++) { s=s*i; sum=sum+s; } printf("%d!=%d\n",n,s); printf("%d的阶乘和为:%d\n",n,sum); return 0; }
(3) Run the above code to realize the calculation of n factorial
Summary: The above is the entire content of this article Okay, hope it helps everyone
The above is the detailed content of How to calculate the factorial of n in c language. For more information, please follow other related articles on the PHP Chinese website!