gpt4 book ai didi

python - 我想选择一些随机数,但在 Python 中它们的相加应该始终是偶数

转载 作者:行者123 更新时间:2023-12-02 02:34:06 25 4
gpt4 key购买 nike

import random


for i in range(100):
a = random.randint(1, 20)
b = random.randint(1, 20)
c = random.randint(1, 20)
if ((a + b + c) % 2) == 0:
print(str(a) + "," + str(b) + "," + str(c))

我尝试了这个,但没有得到所需的输出。我希望在 1 到 20 之间选择三个随机数,使它们的总和始终为偶数。这里程序只打印输出,即使它没有以这种方式选择数字。希望你能帮助我。谢谢!

最佳答案

检查前两个 (a, b) 之和是偶数还是奇数,然后相应地设置 c 怎么样?

import random


for i in range(100):
a = random.randint(1, 20)
b = random.randint(1, 20)
if (a + b) % 2 == 0:
c = random.randint(1, 10) * 2
else:
c = random.randint(1, 10) * 2 - 1
if ((a + b + c) % 2) == 0:
print(str(a) + "," + str(b) + "," + str(c))

关于python - 我想选择一些随机数,但在 Python 中它们的相加应该始终是偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64587911/

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