簡體   English   中英

名稱未定義,即使使用全局變量?

[英]Name not defined, even with global variable?

所以我試圖寫一個 function 來計算 pi 的估計值,然后從 pi 的實際值中減去。 但是,當我運行它時,我收到一條錯誤消息,提示未定義名稱“piCalc”。 關於我做錯了什么的任何想法?

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(piCalc)
  print(difference)
main()

嘗試這樣的事情,你會得到一個錯誤,因為你的價值不是全局的。 這樣,computPI 無論如何都會返回 piccalc,因此您只需獲取返回值即可。

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
   throws = int(input(""))
   calc = computePI(throws)
   difference = calc - math.pi
   print(calc)
   print(difference)
main()

您尚未在 function 中聲明全局

import math
import random
def computePI (numThrows):
  global piCalc
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(piCalc)
  print(difference)
main()

在主 function 中初始化 piCalc,代碼表示 piCalc = 0

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc 
  piCalc = 0
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(difference)
main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM