How to calculate the factorial of an integer n in the C language?

To calculate the factorial of an integer n, you can use a loop structure. Here is an example of C code to calculate the factorial of an integer n:

#include <stdio.h>

int main() {
    int n, i;
    long long factorial = 1;

    printf("请输入一个整数:");
    scanf("%d", &n);

    // 计算阶乘
    for (i = 1; i <= n; i++) {
        factorial *= i;
    }

    printf("%d 的阶乘为 %lld\n", n, factorial);

    return 0;
}

In this example, the user is required to input an integer n, then utilize a loop structure to calculate the factorial of n and print out the result. It is important to note that due to the potentially large size of the factorial result, a long long data type should be used to store the result.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds