The following code snippet calculates the average of 3 numbers. The average is rounded by different rounding methods.
Line | Description |
---|---|
1 | Function header of the function roundDouble() with the input parameters value and decimalPoints |
2 | The pow() method calculates the power of a number by raising the first argument (10) to the second argument (decimalPoints ) |
3 | Returns the rounded value |
6 – 8 | Initializes the variables a , b and c with the values 11.54, 7.73 and 10.54 |
10 | Calculates the average of variable a , b and c |
12 | Outputs the 3 numbers and the average value (without rounding) |
13 | Outputs 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")
Average of 11.54, 7.73 and 10.54 is: 9.936666666666666
Rounded value:
10
9.94