Home >Backend Development >C#.Net Tutorial >How to implement factorial in c language

How to implement factorial in c language

藏色散人
藏色散人Original
2020-05-12 11:50:1336954browse

How to implement factorial in c language

How to implement factorial in c language

Enter a number from the keyboard and find the factorial of this number, that is n!.

Algorithmic Thought

First of all, we must be clear about the definition of factorial. The so-called factorial of n means starting from 1 and multiplying by a number that is 1 larger than the previous number, until n , expressed as a formula: 1×2×3×4×…×(n-2)×(n-1)×n=n!

Specific operation: Use loops to solve problems, set loop variables is i, the initial value is 1, i changes from 1 to n; multiply i and sum in turn, and assign the product to sum.

① Define the variable sum and assign it an initial value of 1.

② i increases by 1.

③ Until i exceeds n.

Program code

#include <stdio.h>
int main()
{
    int i,n;
    double sum=1;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        sum=sum*i;
    printf("%d!=%lf",n,sum);
    printf("\n");
    return 0;
}

Debug operation result

Input 5, the corresponding factorial output is as follows;

5
5!=120.000000

Input 20, the corresponding factorial output The situation is as follows:

20
20!=2432902008176640000.000000

Summary

① Since the factorial is generally large, it will exceed the range that integers or even long integers can represent, so define variables When it is used, it cannot be defined as an integer, but a double precision number should be considered.

② During the training, a double-precision variable was defined to store the results. Therefore, you should pay attention to the output format of double precision numbers when outputting.

Recommended tutorial: c language tutorial

The above is the detailed content of How to implement factorial in c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn