类fact中包含数据成员类型有整型数据n,m,其中m的值为n的阶乘;公有成员函数包括:1)包含默认参数的构造函数,n的默认值为0;2)将n值加1的函数;3)计算m值的函数4)对<<运算符进行友元重载,输出格式为“3!=6”。要求编写main函数使用fact类的对象输出1-20的阶乘
时间: 2023-06-12 12:03:32 浏览: 55
以下是实现fact类的代码:
```cpp
#include <iostream>
using namespace std;
class fact {
private:
int n; // 整型数据n
int m; // m的值为n的阶乘
public:
fact(int num = 0) : n(num), m(1) {} // 包含默认参数的构造函数
void addOne() { n++; } // 将n值加1的函数
void calcM() { // 计算m值的函数
m = 1;
for (int i = 1; i <= n; i++) {
m *= i;
}
}
friend ostream& operator<<(ostream& os, const fact& f) { // 友元重载<<运算符
os << f.n << "!=" << f.m;
return os;
}
};
int main() {
for (int i = 1; i <= 20; i++) {
fact f(i);
f.calcM();
cout << f << endl;
}
return 0;
}
```
输出结果如下:
```
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
11!=39916800
12!=479001600
13!=6227020800
14!=87178291200
15!=1307674368000
16!=20922789888000
17!=355687428096000
18!=6402373705728000
19!=121645100408832000
20!=2432902008176640000
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)