Average of 3 numbers (included number rounding)

The following code snippet calculates the average of 3 numbers. The average is rounded by different rounding methods.

Code Explanation

LineDescription
1Function header of the function roundDouble() with the input parameters value and decimalPoints
2The pow() method calculates the power of a number by raising the first argument (10) to the second argument (decimalPoints)
3Returns the rounded value
6 – 8Initializes the variables a, b and c with the values 11.54, 7.73 and 10.54
10Calculates the average of variable a, b and c
12Outputs the 3 numbers and the average value (without rounding)
13Outputs the mean value via the round() function. Since no decimal places were specified, the number is rounded to 0 decimal places. In addition, the rounded value is output with 2 decimal places via the roundDouble() function
def roundDouble(value, decimalPoints):
    d = pow(10, decimalPoints)
    return round(value * d) / d


a = 11.54
b = 7.73
c = 10.54

avg = (a + b + c) / 3

print("Average of " + repr(a) + ", " + repr(b) + " and " + repr(c) + " is: " + repr(avg))
print("Rounded value:\n" + repr(round(avg)) + "\n" + repr(roundDouble(avg, 2)) + "\n")
Output
Average of 11.54, 7.73 and 10.54 is: 9.936666666666666
Rounded value:
10
9.94