This Python code defines a function roundDouble()
that rounds a given float value
to a specified number of decimal points. The function calculates the power of 10 based on decimalPoints
, multiplies the value
by this power, rounds the result, and then divides by the power to achieve the desired precision. The code then calculates the average of three numbers a
, b
, and c
, prints the average, and prints both the rounded integer and the rounded double to two decimal places.
def roundDouble(value, decimalPoints):
# Calculate the multiplier as 10 raised to the power of decimalPoints
d = pow(10, decimalPoints)
# Round the value after shifting the decimal point to the right and then reposition the decimal point
return round(value * d) / d
# Initialize variables
a = 11.54
b = 7.73
c = 10.54
# Calculate the average of a, b, and c
avg = (a + b + c) / 3
# Print the average with details
print("Average of " + repr(a) + ", " + repr(b) + " and " + repr(c) + " is: " + repr(avg))
# Print the rounded values: nearest integer and to 2 decimal places
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
roundDouble
Functiondef roundDouble(value, decimalPoints):
# Calculate the multiplier as 10 raised to the power of decimalPoints
d = pow(10, decimalPoints)
# Round the value after shifting the decimal point to the right and then reposition the decimal point
return round(value * d) / d
value
: The number to be rounded.decimalPoints
: The number of decimal places to round to.d = pow(10, decimalPoints)
: Computes the multiplier as 10decimalPoints10decimalPoints.round(value * d) / d
: Shifts the decimal point to the right by multiplying by d
, rounds the value, then repositions the decimal point by dividing by d
.a = 11.54
b = 7.73
c = 10.54
a
, b
, and c
with specific values.avg = (a + b + c) / 3
a
, b
, and c
.print("Average of " + repr(a) + ", " + repr(b) + " and " + repr(c) + " is: " + repr(avg))
repr(a)
, repr(b)
, repr(c)
: Converts the values of a
, b
, and c
to strings for printing.print("Rounded value:\n" + repr(round(avg)) + "\n" + repr(roundDouble(avg, 2)) + "\n")
round(avg)
: Rounds the average to the nearest integer.roundDouble(avg, 2)
: Rounds the average to 2 decimal places using the roundDouble
function.