[9]找出一个整型数组中的元素的最大值。要求:编一个基于对象的程序,在类中有2个私有 数据成员(一个一维数组,一个最大值),3个公有的成员函数分别完成一维数组的输入、 求最大值、和输出最大值.用c++
时间: 2024-03-19 19:44:50 浏览: 66
好的,我来为您编写一个基于对象的程序来解决这个问题。
```cpp
#include <iostream>
using namespace std;
class MaxArray {
private:
int arr[100];
int maxVal;
public:
void inputArray(int n) {
cout << "请输入" << n << "个整数:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
}
void getMax(int n) {
maxVal = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
}
void outputMax() {
cout << "数组中的最大值为:" << maxVal << endl;
}
};
int main() {
MaxArray maxArr;
int n;
cout << "请输入数组的元素个数:" << endl;
cin >> n;
maxArr.inputArray(n);
maxArr.getMax(n);
maxArr.outputMax();
return 0;
}
```
程序中定义了一个 `MaxArray` 类,其中有两个私有的数据成员 `arr` 和 `maxVal`,分别表示输入的一维数组和最大值。
公有的成员函数有:
- `inputArray(int n)`:输入一维数组,n 表示数组元素个数。
- `getMax(int n)`:求出一维数组中的最大值,n 表示数组元素个数。
- `outputMax()`:输出一维数组的最大值。
在 `main` 函数中,首先要输入数组的元素个数,然后调用 `MaxArray` 类的成员函数完成输入、求最大值和输出最大值的操作。
阅读全文
相关推荐














