问题
给你 N 个数(N≤100),每个数都在(0∼1000)之间,其中由很多重复的数字,请将重复的数字只保留一个,并将剩下的数由小到大排序并输出。
1.分析问题
- 已知:N个数
- 未知:输出数列
- 关系:重复的数字只保留一个,并将剩下的数由小到大排序
2.定义变量
x:当前输入的数。
count:实际输入的个数,用来控制数组下标
f:判断是否重复。
//二、数据定义
int a[100],n,x,count=0;
bool f;
3.输入数据
读入每个元素都判断一下数组中是否存在该元素。如果存在就不存入数组,如果不存在再存储。
//三、数据输入
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
f=false;
for(int j=0;j<count;j++){
if(x==a[j]){
f=true;
break;
}
}
if(f==false){
a[count]=x;
++count;
}
}
4.数据计算
冒泡排序。
//四、数据计算
//排序
for(int i=0;i<count;i++){
for(int j=0;j<count-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
5.输出结果
#include<iostream>
using namespace std;
int main(){
//一、分析问题
//已知:N个数
//未知:输出数列
//关系:重复的数字只保留一个,并将剩下的数由小到大排序
//二、数据定义
int a[100],n,x,count=0;
bool f;
//三、数据输入
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
f=false;
for(int j=0;j<count;j++){
if(x==a[j]){
f=true;
break;
}
}
if(f==false){
a[count]=x;
++count;
}
}
//四、数据计算
//排序
for(int i=0;i<count;i++){
for(int j=0;j<count-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
//五、输出结果
cout<<count<<endl;
for(int i=0;i<count;i++){
cout<<a[i]<<endl;
}
return 0;
}