2017-04-06 122 views
0

這是我的代碼:功能在for循環

import random 

a = 10000 
b = random.random() 
c = 2 

def random1(a,b,c): 
    z = a * b * c 
    print(z) 

def random2(): 
    for i in range(10): 
     random1(a,b,c) 

random2() 

我有我的輸出問題,因爲功能random2()給了我十個一模一樣的數字,例如:

10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 
10652.014111193188 

錯誤在哪裏?或者我不能使用在for循環中給我隨機數的函數:/。一切都很好,當我循環公式而不是功能時,問題只顯示功能在for循環。

+1

中沒有任何'random1'或'random2'隨機的。這裏唯一的RNG調用是'b = random.random()',它獲得**一個隨機數**並將其分配給'b'。它不會使「b」簡寫爲「call'random.random」 – user2357112

+2

或換句話說,「我擲了一次骰子,看了10次,每次都看到相同的數字!是什麼給了?「 – user2357112

+0

嘗試'b = random.random',然後稱它爲'random1(a,b(),c)'。 –

回答

1

一個簡單的改變應該這樣做,結合brandom.random,然後調用b()同時傳遞到random1

import random 

a = 10000 
b = random.random 
c = 2 

def random1(a,b,c): 
    z = a * b * c 
    print(z) 

def random2(): 
    for i in range(10): 
     # call b() here instead of b 
     random1(a,b(),c) 

random2() 
+0

很好,這對我很有用。 –

0

b永遠不會改變,即使您使用隨機值初始化它。 ac都不會發生變化,但您可能已經預料到了這一點。

0

其實你不應該把B插入隨機函數在所有!如果你想要的功能Random1創建乘以A和C的隨機數:

進口隨機

a = 10000 
# remarked: b = random.random() 
c = 2 

def random1(a,c): 
    b = random.random() 
    z = a * b * c 
    print(z) 



def random2(): # I would call it testRandom1 
    for i in range(10): 
     random1(a ,c) 

random2() # test random1 ten times.