基础数学计算混乱

2024-06-16 11:47:04 发布

您现在位置:Python中文网/ 问答频道 /正文

写一个基本的数学程序,帮助我理解python的数学计算。你知道吗

如果我写

x = 15 + 30 + 45
print(x)

我明白了

90

如果我写

x = 90 / 3
print(x)

我明白了

30.0

但如果我写

def avg3():
    print("This program will calculate the average of 3 scores")
    scores = eval(input("enter 3 scores: "))
    average = scores[0] + scores[1] + scores[2] / 3
    avg = str(average)
    print("The average of the input scores is " + avg + ".")

avg3()

和输入

15, 30, 45

返回的是

The average of the input scores is 60.0.

我当然要30岁。这是怎么回事?你知道吗


Tags: ofthe程序inputisdef数学this
3条回答

实际上,您的代码是这样做的:

average = 15+30+(45/3) #that's because / has higher precedence than +

为了避免使用括号:

average = (scores[0] + scores[1] + scores[2]) / 3

顺便说一句,不要用eval()来表示:

>>> inp=input("enter 3 scores: ")
enter 3 scores: 1,5,6
>>> scores=list(map(int,inp.split(",")))
>>> scores
[1, 5, 6]

除法优先于加法,因此应使用括号:

average = (scores[0] + scores[1] + scores[2]) / 3

平均数中需要括号,如下所示:

average = (scores[0] + scores[1] + scores[2]) / 3

否则,就是用scores[2]除以3。你知道吗

相关问题 更多 >