首页 > 解决方案 > 如何在 Python 中使用 round() 函数?

问题描述

我想知道如何使用 round() 函数。在代码中,它3.75为我显示,但我希望它显示4

我的代码

import random

def dice():

    count = 0
    n = input( "Enter # of dice [3, 6]: " )
    n = int( n )
    diceList = []
    for row in range(0, n):
        diceList.append(random.randint(1, 6))
        count += 1

    print( "\nYou have rolled: ",diceList)

    total=sum(diceList)

    count = round()

    print("The sum is", total, "and the average rounded value is", total / count)


dice()

我希望它看起来如何

Enter # of dice [3, 6]: 4

You have rolled: [3, 4, 5, 6]

The sum is 15, and the average rounded value is 4.

标签: python

解决方案


目前,您有一个TypeError因为没有参数调用轮。round 需要 1 个 arg,这是要四舍五入的值。

您应该将函数的最后两行更改为:

average = round(total/count)
print("The sum is", total, "and the average rounded value is", average)

推荐阅读