自定义数组类ArrayClass: 1个属性:int arr[ ] ; 方法: init()方法:通过键盘输入整数n,为属性arr创建n个元素空间,通过键盘输入n个数存在属性数组arr中; max()方法:返回属性arr中的最大值; search()方法:有一个整型形式参数,在属性arr中查找该整型参数,如果找到了返回true,否则返回false; sum()方法:返回属性arr中所有元素的和; average()方法:返回属性arr中所有元素的平均值; out()方法:输出属性arr中的所有元素的值; main()方法:创建该类对象;调用init方法初始化对象的属性数组;接着调用out方法输出数组元素的值;接着通过键盘输入一个整数,查找该整数是否在数组中,并输出结果;最后输出数组中的最大值,和,平均值
时间: 2023-06-25 12:07:45 浏览: 26
以下是一个实现上述要求的ArrayClass类的示例代码:
```cpp
#include <iostream>
using namespace std;
class ArrayClass {
private:
int* arr;
int n;
public:
void init() {
cout << "请输入数组元素个数n:";
cin >> n;
arr = new int[n];
cout << "请输入" << n << "个整数:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
}
int max() {
int max_val = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
bool search(int val) {
for (int i = 0; i < n; i++) {
if (arr[i] == val) {
return true;
}
}
return false;
}
int sum() {
int sum_val = 0;
for (int i = 0; i < n; i++) {
sum_val += arr[i];
}
return sum_val;
}
float average() {
return (float)sum() / n;
}
void out() {
cout << "数组元素为:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
ArrayClass array;
array.init();
array.out();
int val;
cout << "请输入要查找的整数:";
cin >> val;
if (array.search(val)) {
cout << "找到了" << endl;
} else {
cout << "没找到" << endl;
}
cout << "最大值为:" << array.max() << endl;
cout << "和为:" << array.sum() << endl;
cout << "平均值为:" << array.average() << endl;
return 0;
}
```
使用该类的示例如下:
```
请输入数组元素个数n:5
请输入5个整数:
3 5 -1 4 2
数组元素为:3 5 -1 4 2
请输入要查找的整数:-1
找到了
最大值为:5
和为:13
平均值为:2.6
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)