c++实现计算n的阶乘
时间: 2024-01-25 20:40:55 浏览: 37
好的,这是一个数学问题,我可以回答。计算n的阶乘可以使用循环或递归方法实现。以下是使用循环的代码实现:
```
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
```
使用递归的代码实现如下:
```
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
```
希望对您有帮助!
相关问题
如何用c++计算n的阶乘
您好,可以使用以下代码计算n的阶乘:
```c
#include <stdio.h>
int main() {
int n, i;
long long factorial = 1;
printf("请输入一个正整数:");
scanf("%d", &n);
// 如果n小于,输出错误信息
if (n < )
printf("错误!负数没有阶乘。");
else {
for (i = 1; i <= n; ++i) {
factorial *= i; // 阶乘计算
}
printf("%d 的阶乘为 %lld", n, factorial);
}
return ;
}
```
用C++计算10000的阶乘
计算 10000 的阶乘比较大,无法用普通的数据类型存储,需要使用高精度计算方法。以下是一个使用 C++ 语言实现高精度阶乘计算的示例代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
const int BASE = 10000; // 进制
const int WIDTH = 4; // 数组元素宽度
vector<int> mul(const vector<int>& a, int b) { // 高精度乘法
vector<int> c;
int carry = 0;
for (int i = 0; i < a.size(); i++) {
int t = a[i] * b + carry;
c.push_back(t % BASE);
carry = t / BASE;
}
while (carry > 0) {
c.push_back(carry % BASE);
carry /= BASE;
}
return c;
}
void print(const vector<int>& a) { // 输出
printf("%d", a.back());
for (int i = a.size() - 2; i >= 0; i--)
printf("%04d", a[i]);
printf("\n");
}
int main() {
vector<int> a;
int n = 10000;
a.push_back(1);
for (int i = 2; i <= n; i++)
a = mul(a, i);
printf("%d! = ", n);
print(a);
return 0;
}
```
上述代码中,定义了一个 mul() 函数,用于实现高精度乘法,将一个 vector<int> 与一个整数相乘得到一个新的 vector<int>。print() 函数用于输出 vector<int>。
在主函数中,定义一个 vector<int> a,将 1 放入其中,循环计算出 2~10000 的阶乘,将结果存储在 a 中。最后输出 a 的值即可得到 10000 的阶乘。
需要注意的是,由于计算的结果比较大,需要将进制和数组元素宽度分别设置为合适的值,同时输出时需要将结果按照进制拆分成若干段进行输出。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)