这是我的代码:
def start():
#main input variable to get a sign to do
calculator = input('What would you like to calculate? (x, /, +, -): ')
#gets 2 #'s to multiply, add, subtract, or divide
if (calculator) == ('+'):
add = input('what is the frist number would you like to add? ')
addi = input('what is the second number would you like to add? ')
elif (calculator) ==('-'):
sub = input('what is the first number would you like to subtract? ')
subt = input('what is the second number you would like to subtract? ')
elif (calculator) == ('/'):
div = input('what is the first number would you like to divide? ')
divi = input('what is the second number would you like to divide? ')
elif (calculator) == ('x'):
mult = input('what is the first number would you like to multiply? ')
multi = input('what is the second number would you like to multiply? ')
#failsafe if done incorrect
elif (calculator) != ('x', '/', '-', '+'):
print('try again')
return
#adds 2 inputted #'s
if calculator == '+' :
sumAdd = float (add) + float (addi)
print(sumAdd)
#multiplies the 2 inputted #'s
elif calculator == 'x' :
sumMul = float (mult) * float (multi)
print(sumMul)
#divides the 2 inputted #'s
elif calculator == '/' :
sumDiv = float (div) / float (divi)
print(sumDiv)
#subtracting the 2 inputted #'s
elif calculator == '-' :
sumSub = float (sub) - float (subt)
print(sumSub)
#returns to top of code to do another setup
return
start()
这很简单,我明白了。可以返回数字/整数,但我是从头开始做的,对此我感到满意
只是想知道如何在不执行更多代码的情况下获得超过16个小数。还查看是否有比示例更好的值:(float)或(int)来完成这项工作。如果不是很好 公开回答您是否有任何疑问 谢谢!
答案 0 :(得分:1)
编辑:注释正确,format()
不准确。
您可以使用decimal模块。
from decimal import *
getcontext().prec = 6 #set the number of decimals you prefer
Decimal(1) / Decimal(7)
>>> Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
>>> Decimal('0.1428571428571428571428571429')
答案 1 :(得分:1)
尝试使用decimal
模块:
from decimal import Decimal, getcontext
# set desired precision, 30 for example
getcontext().prec = 30
# normal
print(1 / 7)
# 0.14285714285714285
# with Decimal
print(Decimal(1) / Decimal(7))
# 0.142857142857142857142857142857