顺序表的简单应用代码以及运行结果
时间: 2023-11-14 07:04:35 浏览: 60
顺序表是一种基础数据结构,通常用于存储线性数据。下面是一个简单的顺序表应用示例,用于存储一组整数并输出它们的平均数。
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
class SeqList {
private:
int data[MAXSIZE];
int length;
public:
SeqList() {
length = 0;
}
~SeqList() {}
void insert(int x) {
if (length >= MAXSIZE) {
cout << "Error: the list is full." << endl;
return;
}
data[length++] = x;
}
void print() {
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
cout << endl;
}
double average() {
if (length == 0) {
cout << "Error: the list is empty." << endl;
return 0;
}
int sum = 0;
for (int i = 0; i < length; i++) {
sum += data[i];
}
return (double)sum / length;
}
};
int main() {
SeqList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.print();
cout << "The average is " << list.average() << endl;
return 0;
}
```
运行结果如下:
```
1 2 3 4
The average is 2.5
```