ZBLOG

#include #include #include using namespace std; struct LNode { // 存储数据 int month; int day; string name; double price; }; class List { public: int _size; // 当前元素个数 int capacity; // 顺序表容量...

修改后的代码如下所示:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

struct LNode {
    // 存储数据
    int month;
    int day;
    string name;
    double price;
};

class List {
public:
    int _size;  // 当前元素个数
    int capacity;  // 顺序表容量
    LNode* data;  // 数据数组

public:
    List(int cap) : _size(0), capacity(cap), data(new LNode[cap]) {}
    ~List() { delete[] data; }

    void insert(int index, int a, int b, const string& c, double d) {
        if (index < 0 || index > _size) {
            return;
        }
        if (_size == capacity) {
            resize();  // 扩容
        }
        for (int i = _size - 1; i >= index; --i) {
            data[i + 1] = data[i];  // 元素后移
        }
        data[index].month = a;
        data[index].day = b;
        data[index].name = c;
        data[index].price = d;
        ++_size;
    }

private:
    void resize() {
        capacity *= 2;
        LNode* newData = new LNode[capacity];
        for (int i = 0; i < _size; ++i) {
            newData[i] = data[i];
        }
        delete[] data;
        data = newData;
    }
};

int main() {
    int m, n;
    string str, c;
    double d;

    cin >> m >> n;
    List L1(m);

	for (int i = 0; i < m; ++i) {
		cin >> str >> c >> d;
		int a = stoi(str.substr(0, 2));
		int b = stoi(str.substr(3, 2));

		L1.insert(i, a, b, c, d);
	}

	double sum1 = 0;
	int count1 = 0;
	double sum2 = 0;
	int count2 = 0;

	for (int i = 0; i < m; ++i) {
		if (count1 >= n) {
			break;
		}
		else {
			if (L1.data[i].name == "keyboard") {
				sum1 += L1.data[i].price;
				++count1;
			}
		}
	}

	for (int i = 0; i < m; ++i) {
        if (count2 >= n) {
            break;
        }
        else {
            if (L1.data[i].name == "mouse") {
                sum2 += L1.data[i].price;
                ++count2;
            }
        }
    }

    cout << fixed << setprecision(1) << sum1 / n << endl
         << fixed << setprecision(1) << sum2 / n << endl;

    return 0;
}

这个程序读取了m和n的值,然后创建了一个长度为m的顺序表L1。之后,根据输入的数据依次将元素插入到顺序表中。

接着,通过遍历顺序表L1计算键盘(keyboard)和鼠标(mouse)的平均价格,并输出结果。

请注意,在修改代码时我移除了未定义的”located”函数。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9432

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?