Другие языки программирования и технологии

Описать функцию в c++, которая находит среднее арифметическое значение всех элементов сформированного непустого списка

// шаблон элемента списка
template <class>
class ListNode
{
public:
ListNode(const T &InitValue) : m_pNext(NULL), m_Value(InitValue) {};
~ListNode() {};

ListNode* m_pNext; // указатель на следующий элемент списка
T m_Value; // значение элемента списка
};

// шаблон функции среднего значения списка
template <class>
BOOL GetAverage(const ListNode<t> *pHead, double &Average)
{
if (pHead)
{
const ListNode<t> *pNode = pHead;
double Summ = 0;
int nCount = 0;
do
{
nCount++;
Summ += pNode->m_Value;
pNode = pNode->m_pNext;
} while (pNode);
Average = Summ / nCount;
return TRUE;
}
return FALSE;
}

// Шаблон очистка списка
template <class>
void FreeList(ListNode<t> *&pHead)
{
while (pHead)
{
ListNode<t> *pNode = pHead;
pHead = pNode->m_pNext;
delete pNode;
}
}

// Инициализация списка, сделаешь сам
BOOL InitList(ListNode<int> *&pHead)
{
ListNode<int> *pNode = pHead = new ListNode<int>(0);
for (int i = 1; i < 10; i++)
{
pNode = pNode->m_pNext = new ListNode<int>(i);
}
return TRUE;
}

int main()
{
ListNode<int> *pHead = NULL;

if (InitList(pHead))
{
double Average;
if (GetAverage(pHead, Average))
{
printf("Среднее = %g\n", Average);
}
FreeList(pHead);
}
return 0;
}
АБ
Александр Беркудалов
21 360
Лучший ответ
Поточнее:

double srednee (double *mas,int n)
{
double summ=0;

for(int i=0;i < n;i++)
{
summ+=mas;
}

return summ/n;
}
ЮМ
Юрий Мотков
5 305
int srednee (int *mas,int n)
{
int summ=0;

for(int i=0;i < n;i++)
{
summ+=mas;
}

return summ/n;
}
double Avg(const std::vector<double>& values)
{
if (values.empty())
return 0;

return std::accumulate (values.begin (), values.end(), 0) / values.size();
}
Ко
Коттон
2 702

Похожие вопросы