这是一个创建于 2477 天前的主题,其中的信息可能已经有所发展或是发生改变。
1. A function that formats a positive decimal number e.g. 12.345 into a string representation of the number with a specified number of digits after the decimal point e.g. “ 12.35 ”. This function is useful in generating report for customer where you don ’ t want to present all the digits after the decimal point – as these are unnecessarily precision e.g. $12.345 is not much different from $12.346.
The following is the interface (also called, application program interface) of this function:
#*************************************************************************
# format(x, digits)
# format the input number x with the specified number of digits after the
# decimal point.
#
# inputs:
# x: a positive number in float or integer
# digits: number of digits after the decimal point
#
# returns: a string representation of the input number x rounded to the
# specified number of digits after the decimal point.
#
# example:
# >>> format(12.34,1)
# >>> 12.3
# >>> format(12.345, 2)
# >>> 12.35
# >>> format(12.99,1)
# >>> 13.0
#*************************************************************************
For this assignment you canNOT use Python ’ s String format() functions or the function round(). This exercise is design to give you the opportunity to think about String formatting. For future assignment, you may (and should) use these built-in functions whenever possible.
Hint. You may need to use the following “ in-line ” if-statement.
>>> a = 3
>>> "a is greater than 3" if a>3 else "a is not greater than 3"
'a is not greater than 3'
>>> "a is greater than or equal to 3" if a>=3 else "a is less than 3"
'a is greater than or equal to 3'
>>> "a is equal to 3" if a==3 else "a is not equal to 3"
'a is equal to 3'
>>> "a is 3" if a==3 else ("a greater than 3" if a>3 else "a less than 3")
'a is 3'
>>> a = 2
>>> "a is 3" if a==3 else ("a greater than 3" if a>3 else "a less than 3")
'a less than 3'
>>> a = 4
>>> "a is 3" if a==3 else ("a greater than 3" if a>3 else "a less than 3")
'a greater than 3'