This code snippet calculates the volume and surface area of a sphere given its radius, and then truncates the results to a specified number of decimal places before printing them.
import math
def getVolume(r):
return ((4 * math.pi * pow(r, 3)) / 3)
def getSurfaceArea(r):
return 4 * math.pi * pow(r, 2)
def truncate(n, d=0):
m = 10 ** d
return int(n * m) / m
radius = int(input("Please enter radius: "))
volume = truncate(getVolume(radius), 2)
area = truncate(getSurfaceArea(radius), 2)
print("Volume: " + repr(volume))
print("Surface: " + repr(area))
Please enter radius: 4
Volume: 268.08
Surface: 201.06
import math
math module, which provides access to mathematical functions like math.pi and pow().getVolume(r)def getVolume(r):
return ((4 * math.pi * pow(r, 3)) / 3)
r, which is the radius of the sphere.math.pi provides the value of π (pi).pow(r, 3) raises the radius r to the power of 3.getSurfaceArea(r)def getSurfaceArea(r):
return 4 * math.pi * pow(r, 2)
r, which is the radius of the sphere.math.pi provides the value of π (pi).pow(r, 2) raises the radius r to the power of 2.truncate(n, d=0)def truncate(n, d=0):
m = 10 ** d
return int(n * m) / m
n to d decimal places.n: The number to be truncated.d: The number of decimal places to keep (default is 0).m = 10 ** d: Raises 10 to the power of d to create a multiplier.int(n * m) / m: Multiplies n by m, converts it to an integer to drop any fractional part, and then divides by m to scale it back down.radius = int(input("Please enter radius: "))
int(), and stored in the variable radius.volume = truncate(getVolume(radius), 2)
area = truncate(getSurfaceArea(radius), 2)
getVolume(radius) calculates the volume of the sphere using the input radius.truncate(..., 2) truncates the volume to 2 decimal places.getSurfaceArea(radius) calculates the surface area of the sphere using the input radius.truncate(..., 2) truncates the surface area to 2 decimal places.print("Volume: " + repr(volume))
print("Surface: " + repr(area))
repr() and concatenated with the label “Volume: “, then printed.repr() and concatenated with the label “Surface: “, then printed.