首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >输入两个闭区间,求其交集,并集和差集(C++)

输入两个闭区间,求其交集,并集和差集(C++)

作者头像
Enjoy233
发布2019-03-05 11:02:07
1.7K0
发布2019-03-05 11:02:07
举报

输入两个闭区间,求其交集,并集和差集(C++)

C++:

#include<iostream>using namespace std;
int main() {
	int a,b;
	int c,d;
	cout<<"请输入第一个闭区间的a,b"<<endl;
	cin>>a>>b;
	cout<<"请输入第二个闭区间的c,d"<<endl;
	cin>>c>>d;
	if(a>b||c>d) {
		cout<<"输入的区间不合法"<<endl;
	} else {
		if(d<a) {
			cout<<"交集为:空集"<<endl;
			cout<<"并集为:"<<"["<<c<<","<<d<<"]"<<","<<"["<<a<<","<<b<<"]"<<endl;
			cout<<"差集为:"<<"["<<a<<","<<b<<"]"<<endl;
		} else if(c>b) {
			cout<<"交集为:空集"<<endl;
			cout<<"并集为:"<<"["<<a<<","<<b<<"]"<<","<<"["<<c<<","<<d<<"]"<<endl;
			cout<<"差集为:"<<"["<<a<<","<<b<<"]"<<endl;
		} else if(c<a) {
			int min,max;
			if(d>b) min=b,max=d;
			else min=d,max=b;
			cout<<"交集为:"<<"["<<a<<","<<min<<"]"<<endl;
			cout<<"并集为:"<<"["<<c<<","<<max<<"]"<<endl;
			if(d>=b) cout<<"差集为:空集"<<endl;
			else cout<<"差集为:"<<"["<<d-1<<","<<b<<"]"<<endl;
		} else {
			int min,max;
			if(d>b) min=b,max=d;
			else min=d,max=b;
			cout<<"交集为:"<<"["<<c<<","<<min<<"]"<<endl;
			cout<<"并集为:"<<"["<<a<<","<<max<<"]"<<endl;
			if(c<=a) cout<<"差集为:空集"<<endl;
			else {
				cout<<"差集为:"<<"["<<a<<","<<c-1<<"]";
				if(d<b) {
					cout<<","<<"["<<d-1<<","<<b<<"]";
				}
				cout<<endl;
			}
		}
	}
	return 0;
}

perl集合运算之交集,并集,差集

perl中,实现两个集合的运算很简单,只需几行代码即可

Perl代码:

@a=('a'..'c',1..3);  
@b=('A'..'C',1..3);  
@union=();#并集  
@diff=(); #差集   
@isect=();#交集  
foreach $e(@a,@b){  
   $union{$e}++&&$isect{$e}++;  
}  
@union=keys %union;  
@isect=keys %isect;  
@diff=grep {$union{$_}==1;} @union;  
print (join ',',@union);  
print "\n";  
print (join ',',@isect);  
print "\n";   
print (join ',', @diff); 

输出:

Perl代码  

  1. A,a,3,B,2,c,1,C,b  
  2. 1,3,2
  3. A,a,B,c,C,b  
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013年05月31日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • perl集合运算之交集,并集,差集
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档