I want to calculate the average of elements from a linked list:
.h
class List
{
public:
List() { head = NULL; }
void insertNode(int);//inserare nod la sfarsitul unei liste
void printList();//afisare lista
void deleteNode(int);
void medie(float);
.cpp
void List::medie(float) {
int count = 0;
int sum = 0;
int media = 0;
Node* temp3 = head;
while (temp3 != NULL) {
count ;
sum = temp3->val;
temp3 = temp3->next;
}
media = (double)sum / count;
return media;
}
I received this error:
return value type doesn't match the function type
I don't know how to repair it.
CodePudding user response:
The function is declared with the return type void
void medie(float);
So it means that it returns nothing. However within the function definition there is a return statement with a non-void expression.
return media;
So the compiler issues an error message.
Also the function parameter is not used within the function. Its declaration does not make a sense.
In this statement
media = (double)sum / count;
there is no great sense to cast the variable sum
to the type double
because the result is assigned to the variable media
having the type int
.
The function should be declared the following way
double medie() const;
and defined like
double List::medie() const
{
double sum = 0.0;
size_t count = 0;
for ( const Node *temp = head; temp != nullptr; temp = temp->next )
{
sum = temp->val;
count;
}
return count == 0 ? 0.0 : sum / count;
}