Advertisement
KDOXG

Arithmetic Mean by User

Jul 26th, 2019
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. /** Arithmetic Mean by User
  2.  * Implements a linked list that stores sequencial doubles inserted during reading
  3.  * and calculates it's arithmetic mean.
  4.  * The reading stops when the input is not a number.
  5.  * The function returns a double containing the value of the mean.
  6.  *
  7.  * Requires #include <iostream> and <cstdlib>.
  8.  */
  9.  
  10. double Arithmetic_Mean_by_User()
  11. {
  12.     int n=0;
  13.     std::string input = std::string();
  14.    
  15.     struct intList{
  16.         double num;
  17.         struct intList *next;
  18.     } *head, *loop;
  19.     head = (struct intList*)malloc(sizeof(struct intList));
  20.     head->next = NULL;
  21.  
  22.     loop = head;
  23.     while(1)
  24.     {
  25.         std::cin >> input;
  26.         if ((input.c_str())[0] < 48 || (input.c_str())[0] > 57)
  27.             break;
  28.         loop->num = atof(input.c_str());
  29.         n++;
  30.         loop->next = (struct intList*)malloc(sizeof(struct intList));
  31.         loop->next->next = NULL;
  32.         loop = loop->next;
  33.     }
  34.    
  35.     if (n == 0)
  36.         return 0;
  37.    
  38.     double mean=0;
  39.     while (head != NULL)
  40.     {
  41.         mean += head->num;
  42.         loop = head;
  43.         head = head->next;
  44.         free(loop);
  45.     }
  46.     return mean / n;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement