How do you Calculate the average of two numbers then return the average in c plus plus?

1 answer

Answer

1203932

2026-04-27 22:00

+ Follow

Use the following function:

/* returns the average of two real numbers */

double average (const double a, const double b) {

return a/2.0 + b/2.0;

}

Note that we do not use (a+b) / 2.0 because the expression a+b could overflow the range of a double. By dividing each value by 2 before summing we ensure the result can never overflow no matter how large a and b are.

Ideally, you should write separate functions to cater for float and long double arguments independently:

/* returns the average of two long doubles */

long double average_lng (const long double a, const long double b) { return a/2.0 + b/2.0;

}

/* returns the average of two floats */

float average_flt (const float a, const float b) {

return a/2.0F + b/2.0F;

}

For mixed-mode arithmetic, always use the highest precision argument. E.g., the average of a float and a double is a double, so use the function that returns a double, not a float. The float argument will be implicitly cast to a double.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.