We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hello to everyone.
When I have to calculate the average of two integer numbers, first i have to add them. Sometimes an overflow occurs. One technique maybe to compare the result to one of the numbers, if result is lower, an overflow is recognized.
Is this good style or better use Assembler?
the KISS solution avarage = (a/2) + (b/2);
Erik
But the KISS solution yields:
"average of 5 and 7 = 5"
which is not the best integer answer. It all depends on the accuracy that is needed. That said, if being off by one bit every now and then is okay, then it is certainly the fastest solution.
Steph-
The slightly less simple solution fixes that:
average = (a/2) + (b/2) + (a%2 + b%2) / 2;