gpt4 book ai didi

Python 3.x 函数值不正确

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:24 24 4
gpt4 key购买 nike

我不明白为什么我的代码会给我错误的值。作为 Python 的初学者,我正在学习 def()

所以我的代码是:

def secret_formula(started):

jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)

print(f"With a starting point of: {start_point}")
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10

print("We can have also do that this way:")
print("We'd have {} beans, {} jars, and {} crates.".format(beans, jars, crates))

当我运行我的程序时,我的答案是:

With a starting point of: 10000

We'd have 5000000 beans, 5000.0 jars,and 50.0 crates.

We can have also do that this way:

We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.

但我认为应该是:

With a starting point of: 10000

We'd have 5000000 beans, 5000.0 jars,and 50.0 crates.

We can have also do that this way:

We'd have 500000 beans, 500 jars, and 5 crates.

类似的东西...因为 start_point = start_point/10 对吗?

我做错了什么?

Obs:是的,出于测试原因,我使用了不同的方法来“打印”。

最佳答案

你需要像这样记忆secret_formula():

start_point = start_point / 10
beans, jars, crates = secret_formula(start_point)

测试代码:

def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

print(f"With a starting point of: {start_point}")
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10
beans, jars, crates = secret_formula(start_point)

print("We can have also do that this way:")
print("We'd have {} beans, {} jars, and {} crates.".format(beans, jars,
crates))

结果:

With a starting point of: 10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.
We can have also do that this way:
We'd have 500000.0 beans, 500.0 jars, and 5.0 crates.

关于Python 3.x 函数值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com