Suppose you have struct stuff { int x; double y; struct stuff *ptr; }; suppose a
ID: 3715272 • Letter: S
Question
Suppose you have
struct stuff {
int x;
double y;
struct stuff *ptr;
};
suppose a link list of type struct stuff has been generated pointed to by the struct stuff pointer named head. Write a function : double fun (struct stuff * head) that computes the average of all the y's in the link list for which x>0. If no x>0, then return -1.0.
Here's what I have so far. I think I have everything except the situation where no x>0, I'm not sure how to position the return -1.0 instead of the average if there's no x>0 in the link list.
double fun (struct stuff * head)
{
double sum=0;
int count=0;
ptr=head;
while(ptr -> x > 0)
{
sum+=ptr->y;
count++;
ptr=ptr->nextItem;
}
return sum/count;
}
where do I place the return -1.0 if there is no x<0??
Explanation / Answer
Here you should not stop loop if you encounter no x >0. You have to continue the loop until reach the end of the link list. And after loop stops, if there is no x>0 ,i.e., count of nodes which have x >0 is 0, then we return -1.0.
double fun (struct stuff * head)
{
double sum=0;
int count=0;
ptr=head;
while(ptr) //until we reaches the end of the loop
{
if(x > 0){
sum+=ptr->y;
count++;
ptr=ptr->nextItem;
}
}
if(count == 0){ // here count is zero only if there is no x > 0
return (-1.0);
}
// else we will return the average of y's from the list
return sum/count;
}
Hope the answer helps !!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.