in python: how fix the code below so that the output will print out on decimal p
ID: 3861773 • Letter: I
Question
in python: how fix the code below so that the output will print out on decimal place? the rounding should be at the print area.
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
Hi
I have fixed the issue and highlighted the code changes below
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(round(rect.getArea(),1)) + " and a perimeter of " + str(round(rect.getPerimeter(),1)) + ". ");
# 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(round(rect1.getArea(),1)) + " and a perimeter of " + str(round(rect1.getPerimeter(),1)) + ". ");
# Calling main function
main();
Output:
sh-4.3$ python3 main.py
A 4 x 40 rectangle has an area of 160 and a perimeter of 88.
A 3.5 x 35.7 rectangle has an area of 125.0 and a perimeter of 78.4.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.