我一直在写这个程序,目的是在钱箱里加钱。当我开始乘法时,我意识到我需要对代码进行更改。 int(1) * float(0.05)
给了我0.050000000000000003。我尝试搜索如何对其进行四舍五入,但发现float
不能准确表示货币,我还发现了有关decimal
和quatitize ()
的信息。我试图了解如何将其合并到我的代码中,但我一直在努力。如何在我的代码中准确表示货币?
money = {'nickles' : 0, 'dimes' : 0, 'quarters': 0, 'ones': 0, 'twos': 0, 'tens' : 0, 'twenties' : 0, 'fifties': 0, 'one hundreds' : 0}
def display_values():
print(money['nickles'], 'nickles = ', money['nickles'] * 0.05, 'cents')
def assign_all_values():
input_nickles()
input_dimes()
input_quarters()
input_ones()
input_twos()
input_fives()
input_tens()
input_fifties()
input_one_hundreds()
def input_nickles():
money['nickles'] = float(input('how many nickels are in your cash box? '))
display_values()
def input_dimes():
money['Dimes'] = float(input('how many dimes are in your cash box? '))
display_values()
def input_quarters():
money['Quarters'] = float(input('how many quarters are in your cash box? '))
display_values()
def input_ones():
money['Ones'] = int(input('how many one dollar coins are in your cash box? '))
display_values()
def input_twos():
money['twos'] = int(input('how many one two dollar coins are in your cash box? '))
display_values()
def input_fives():
money['fives'] = int(input('how many five dollar bills are in your cash box? '))
display_values()
def input_tens():
money['Tens'] = int(input('how many ten dollar bills are in your cash box? '))
display_values()
def input_twenties():
money['Twenties'] = int(input('how many twenty dollar bills are in your cash box? '))
display_values()
def input_fifties():
money['fifties'] = int(input('how many fifty dollar bills are in your cash box? '))
display_values()
def input_one_hundreds():
money['one hundreds'] = int(input('how many one hundred dollar bills are in your cash box '))
display_values()
def change_value():
entry = input("what value would you like to change?\n1. One dollar")
assign_all_values()
答案 0 :(得分:1)
您在decimal数据类型的正确轨道上。您可以使用小数代替整数和浮点数将其集成到程序中。
首先,导入模块
from decimal import Decimal as D
然后您可以像这样使用它:
money['nickles'] = D(input('how many nickels are in your cash box? '))
您还应该将乘法因子和起始0定义为十进制。然后,您可以像本机python类型一样执行算术运算(在两个十进制值之间)。
请注意,您应将字符串传递给十进制初始化(例如number = D('0.05')
)以获取精确表示
要打印值时,可以使用.quantize(D('1.000'))
舍入到#0的小数位