#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0

    Calculating the mean


    I'm wondering how I can calculate the mean and mode of a group of numbers in C
  2. #2
  3. No Profile Picture
    Mid-level Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    44
    Rep Power
    12
    Sounds like homework to me. Do you have any code we can look at and help you with?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    mmm nm I figured it out :)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    oh and no, it wasn't homework :P
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    Well to correct myself, i've only solved half of my problem.

    Code:
    ( n + 1 ) / 2         // n = number count
    That will solve the mean problem for an odd number but it can't work with an even amount of numbers because you can't use a decimal number for an array subscript. How do I get around this ?
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    I guess I found a solution for my problem.. it might not be the right way.. but it works :)

    numbers[] is an array of user-inputed numbers.
    count is the amount of numbers the user inputed.

    Code:
    float calc_mean( void )
    {
    	int tmp;
    	float mean;
    	
    	tmp = count / 2;    
    	tmp = tmp * 2;
    	
    	if( tmp == count )
    	{
    		tmp = count / 2;
    		mean = ( numbers[tmp - 1] + numbers[tmp] ) / 2;
    	}		
    	else
    	{
    		tmp = ( count + 1 ) / 2 ;
    		mean = numbers[tmp - 1];
    	}
    
    	return mean;
    }
    I devide the total amount of numbers in half and stick the answer in an int so it chops off the decimals. Then I multiply the int by 2 again. If the number *was* even it will return to it's orginal value but if it *isn't* even it won't, because it lost it's decimal and can't make up.

    Thus, you can employ a different stratagy to find your median depending if the amount of numbers is odd or even.

IMN logo majestic logo threadwatch logo seochat tools logo