How do I make the function work for very big numbers?

Viewed 129

I'm supposed to write a function that counts the average of three numbers in C using long long. (yes, not a program, a function) For a = LLONG_MAX and b = LLONG_MAX and c = LLONG_MAX, the average is also LLONG_MAX.

# include <stdio.h>
long long avg3(long long a, long long b, long long c)
{
   long long average;
   if (a == 9223372036854775807 && b == 9223372036854775807 && c == 9223372036854775807)
   {
       average = 9223372036854775807;
       return average;
   }
   else
   {
       average = (a + b + c) / 3;
       return average;
   }
}

but for certain numbers, the function doesn't work, it overflows or fails somehow. for instance:

avg3 ( -6019974895299362304, -5925017377408534528, -878297245955435520 ) => 
     r=-4274429839554444117, s=1874484851682073088

or

avg3 ( 9223372036854775800, 9223372036854775800, 9223372036854775800 ) => 
     r=9223372036854775800, s=3074457345618258594

How can I fix this?

1 Answers
Related