How to change the code below to print the output to one decimal place? class Rec
ID: 3859104 • Letter: H
Question
How to change the code below to print the output to one decimal place?
class Rectangle:
"""
Rectangle class
"""
def __init__(self, width=1, height=2):
"""
Constructor
"""
# Initializing private variables
self.__width = width;
self.__height = height;
def getWidth(self):
"""
Function that returns width of a rectangle
"""
return self.__width;
def getHeight(self):
"""
Function that returns height of a rectangle
"""
return self.__height;
def getArea(self):
"""
Function that returns area of a rectangle
"""
return self.__width * self.__height;
def getPerimeter(self):
"""
Function that returns perimeter of a rectangle
"""
return 2 * (self.__width + self.__height);
def main():
"""
Main function
"""
# Creating object
rect = Rectangle(4, 40);
# Printing data
print(" A " + str(rect.getWidth()) + " x " + str(rect.getHeight()) + " rectangle has an area of " + str(rect.getArea()) + " and a perimeter of " + str(rect.getPerimeter()) + ". ");
# Creating object
rect1 = Rectangle(3.5, 35.7);
# Printing data
print(" A " + str(rect1.getWidth()) + " x " + str(rect1.getHeight()) + " rectangle has an area of " + str(rect1.getArea()) + " and a perimeter of " + str(rect1.getPerimeter()) + ". ");
# Calling main function
main();
Explanation / Answer
class Rectangle:
"""
Rectangle class
"""
def __init__(self, width=1, height=2):
"""
Constructor
"""
# Initializing private variables
self.__width = width;
self.__height = height;
def getWidth(self):
"""
Function that returns width of a rectangle
"""
return self.__width;
def getHeight(self):
"""
Function that returns height of a rectangle
"""
return self.__height;
def getArea(self):
"""
Function that returns area of a rectangle
"""
return round((self.__width * self.__height),1);
def getPerimeter(self):
"""
Function that returns perimeter of a rectangle
"""
return round((2 * (self.__width + self.__height)),1);
def main():
"""
Main function
"""
# Creating object
rect = Rectangle(4, 40);
# Printing data
print(" A " + str(rect.getWidth()) + " x " + str(rect.getHeight()) + " rectangle has an area of " + str(rect.getArea()) + " and a perimeter of " + str(rect.getPerimeter()) + ". ");
# Creating object
rect1 = Rectangle(3.5, 35.7);
# Printing data
print(" A " + str(rect1.getWidth()) + " x " + str(rect1.getHeight()) + " rectangle has an area of " + str(rect1.getArea()) + " and a perimeter of " + str(rect1.getPerimeter()) + ". ");
# Calling main function
main();
# Using the round(val,1) method
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.