在计算机编程中,要找出两个集合中相同的元素(即交集),可以使用不同的编程语言实现。以下是一些常见的编程语言的示例代码:
Python
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection = set1.intersection(set2)
print(intersection)
```
JavaScript
```javascript
const set1 = new Set([1, 2, 3, 4, 5]);
const set2 = new Set([4, 5, 6, 7, 8]);
const intersection = new Set(
[...set1].filter(x => set2.has(x))
);
console.log(intersection);
```
Java
```java
Set
Set
set1.retainAll(set2);
System.out.println(set1);
```
C
```cpp
include
include
include
include
int main() {
std::set
std::set
std::vector
std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::back_inserter(intersection));
for (int num : intersection) {
std::cout << num << " ";
}
return 0;
}
```
这些代码示例展示了如何在Python、JavaScript、Java和C 中找出两个集合的交集。根据你的需求,选择合适的编程语言和方法来实现数字交集的计算。
希望可以帮助到你!