制作一个更精确的程序来计算(例如 2/3),而不仅仅是 16 个字符

这是我的代码:


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) 更好的价值来完成这项工作。如果不是一切都很好,如果您有任何答案,请打开谢谢!


缥缈止盈
浏览 190回答 2
2回答

海绵宝宝撒

试试这个decimal模块:from decimal import Decimal, getcontext# set desired precision, 30 for examplegetcontext().prec = 30# normalprint(1 / 7)# 0.14285714285714285# with Decimalprint(Decimal(1) / Decimal(7))# 0.142857142857142857142857142857

四季花海

评论是正确的,format()是不准确的。您可以使用十进制模块。from decimal import *getcontext().prec = 6 #set the number of decimals you preferDecimal(1) / Decimal(7)>>> Decimal('0.142857')getcontext().prec = 28Decimal(1) / Decimal(7)>>> Decimal('0.1428571428571428571428571429')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python