3

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?

motpfofs
  • 103
  • 1
  • 2
  • 4
slipper13
  • 45
  • 6
  • 1
    See [this](https://stackoverflow.com/questions/23949785/average-of-3-long-integers) and [this](https://stackoverflow.com/questions/64546414/math-operations-with-long-long-in-c). – Eric Postpischil Oct 29 '20 at 12:52

1 Answers1

1

You can use __int128 that let you lot more memory.

GCC documentation

DipStax
  • 343
  • 2
  • 12