下面是使用另一种方法实现给定的代码:
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct LNode
{
//存储数据
int month;
int day;
string name;
double price;
LNode* next;//后继指针
LNode() {};
LNode(int a, int b, string c, double d, LNode* n = NULL) :month(a), day(b), name(c), price(d), next(n) {};
};
class List
{
public:
int _size;
LNode* head;
void init() {
head = new LNode;
head->next = NULL;
_size = 0;
}
List() {
init();
}//构造函数
~List(){//析构函数
LNode* p = head;
while (head)
{
p = p->next;
delete head;
head = p;
}
};
//头插法
void insert(int& a, int& b, string& c, double& d)
{
_size++;
LNode* p = new LNode(a, b, c, d, head->next);
head->next = p;
}
void insert(int index, int a, int b, string c, double d)
{
if(index <= 0 || index > _size + 1){
return;
}
_size++;
LNode* p = head;
for (int i = 0; i < index - 1; i++)
{
p = p->next;
}
LNode* tmp = new LNode(a, b, c, d);
tmp->next = p->next;
p->next = tmp;
}
void print_L()
{
LNode* p = head->next;
while (p)
{
cout << p->month << " " << p->day << " ";
p = p->next;
}
cout << endl;
}
int located(int a, int b)
{
LNode* p = head->next;
int e = 1;
if (p == NULL){
return e;
}
while (p)
{
if (a < p->month)
{
e++;
p = p->next;
if (p == NULL){
return e;
}
}
else if (a > p->month)
{
return e;
}
else if (a == p->month)
{
if (b < p->day)
{
e++;
p = p->next;
if (p == NULL){
return e;
}
}
else if (b > p->day)
{
return e;
}
else if (b == p->day)
{
return e;
}
}
}
}
};
int main()
{
int m, n;
string str;
string c;
double d;
List L1;
double ave1 = 0;
double ave2 = 0;
cin >> m >> n;
for (int i = 0; i < m; i++)
{
cin >> str >> c >> d;
int a = stoi(str.substr(3));
int b = stoi(str.substr(0,2));
int e = L1.located(a, b);
L1.insert(e, a, b, c, d);
}
double sum1 = 0;
int count1 = 0;
double sum2 = 0;
int count2 = 0;
LNode* p = L1.head->next;
for (int i = 0; i < m; i++)
{
if (count1 >= n)
{
break;
}
else
{
if (p->name == "keyboard")
{
sum1 += p->price;
p = p->next;
count1++;
}
else if (p->next != NULL)
{
p = p->next;
}
}
}
LNode* s = L1.head->next;
for (int i = 0; i < m; i++)
{
if (count2 >= n)
{
break;
}
else
{
if (s->name == "mouse")
{
sum2 += s->price;
s = s->next;
count2++;
}
else if (s->next != NULL)
{
s = s->next;
}
}
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
这段代码会产生与原始代码相同的结果,但在某些细节上进行了修改以改进代码的可读性和一致性。例如,将字符串截取操作替换为 substr
函数,更改变量命名以符合常规约定,以及在注释和代码布局方面的一些微小调整。
内容由零声教学AI助手提供,问题来源于学员提问