【问题描述】试定义一个类ARRAY,实现对一维整型数组的排序。排序的规则如下:将一维数组中各元素按其各位的数字之和从小到大排序。具体要求如下:
(1)私有数据成员:
int a[100]; 待排序的数组;
int n; 数组中元素的个数;
(2)公有成员函数
ARRAY(int t[], int m); 构造函数,利用参数t初始化成员a,参数m为数组t中元素的个数,用参数m初始化成员n;
int sum(int x); 求整数x的各位数字之和,并返回该值,此函数供成员函数fun()调用;
void fun(); 按要求对数组a的元素排序;
void print(); 输出数组a的所有元素。
(3)在主函数中对该类进行测试。
【输入形式】无
【输出形式】排序前后的数组对象中的数据。
【样例输入】无
【样例输出】
排序前:297 735 624 158 312 900
排序后:312 900 624 158 735 297
#include <iostream>
using namespace std;
class ARRAY {
private:
int a[100];
int n;
public:
ARRAY(int t[], int m) {
for (int i = 0; i < 100; i++) {
a[i] = t[i];
}
n = m;
}
int sum(int x){
int s=0;
s=x/ 100 + x/ 10 % 10 + x% 100 % 10;
return s;
}
void fun() {
int temp;
for(int i=0;i<n;i++){
for(int j=0;j<n-1-i;j++){
if(sum(a[j])>sum(a[j+1])){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
void print() {
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout<<endl;
}
};
int main()
{ int a[]={297,735,624,158,312,900};
ARRAY arr(a,sizeof(a)/sizeof(int));
cout<<"排序前:";
arr.print();
arr.fun();
cout<<"排序后:";
arr.print ();
return 0;
}