简体   繁体   English

如何打印两次相同的随机数?

[英]How print two times same random number?

I try to make a code that prints two equal random values in a text.我尝试制作一个在文本中打印两个相等随机值的代码。

import random
archivo=open('Ejercicio3.txt', 'w')
up=0
insert=int(input('Valor: '))
for i in range(insert):
    up+=1
    n1=random.randint(10, 100)
    n2=random.randint(10, 100)
    archivo.write(f'{up}.-    {n1} - {n2} = {n1-n2}\n\n')

    print(f'{up}.-    {n1} - {n2} = {n1-n2}')
    archivo.write(f'{n1-n2}\n')#This is the problem, because the code write numbers different random

archivo.close()

What I want is for it to do something similar to this:我想要的是它做类似的事情:

import random
archivo=open('Ejercicio1.1.txt', 'w')
up=0
insert=int(input('Valor: '))
for i in range(insert):
    up+=1
    n1=random.randint(10, 100)
    n2=random.randint(10, 100)

    archivo.write(f'{n1} - {n2} =''\n\n')

up=0
archivo.write('---------------------------------------------\n')
for i in range(insert):
    up+=1
    n1=random.randint(10, 100)
    n2=random.randint(10, 100)
    archivo.write(f'{n1-n2}''\n\n')#Except this part, I want it to be exactly the same as the result of the subtraction above. 
archivo.close()

The result i want, is this: Example我想要的结果是这样的:示例

Someone can I help me?有人可以帮我吗? Thanks very much.非常感谢。 Regards问候

you can use random.seed() and set the same seed two times.您可以使用random.seed()并设置相同的种子两次。

import random

random.seed(0)
print(random.random())
#prints a random number    

random.seed(0)
print(random.random())
#prints the same random number

Just store the results in a list and then iterate over it again.只需将结果存储在列表中,然后再次对其进行迭代。

import random
archivo=open('Ejercicio1.1.txt', 'w')
up=0
results = []
insert=int(input('Valor: '))
for i in range(insert):
    up+=1
    n1=random.randint(10, 100)
    n2=random.randint(10, 100)
    results.append(n1-n2)
    archivo.write(f'{n1} - {n2} = {n1 - n2} ''\n\n')

up=0
archivo.write('---------------------------------------------\n')
for i in range(insert):
    up+=1
    archivo.write(f'{results[i]}''\n\n')
archivo.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM