繁体   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