在线编译器 C

#include <stdio.h> int factorial(int n) { int a = 1; for (int i = 1; i <= n; i++) { a *= i; } return a; }
This code defines a function that calculates the factorial of a given integer `n` by multiplying numbers from 1 to `n` together.

- The function uses a loop to multiply each integer from 1 up to `n` into the variable `a`, which starts at 1.
- Consider what happens when `n` is 0. The factorial of 0 is defined as 1, but the loop condition `i <= n` would not execute, so the function returns 1 correctly. However, think about what happens for negative numbers — the loop would not run, but factorial is not defined for negative integers. You may want to handle that case.
- Also, note that the factorial grows very quickly. For large values of `n`, the result may exceed the range of an `int`, causing overflow. You might consider using a larger data type like `long long` if needed.