如何在def(Python)中使用输入
说到编码,我是个新手。如果您能帮助我解决编码方面的问题,我将不胜感激。我尝试在def中使用输入,但不起作用如何在def(Python)中使用输入,python,function,random,input,pi,Python,Function,Random,Input,Pi,说到编码,我是个新手。如果您能帮助我解决编码方面的问题,我将不胜感激。我尝试在def中使用输入,但不起作用 import random def estimate_pi(n): num_point_circle = 0 num_point_total = 0 for _ in range(n): x = random.uniform(0,1) y = random.uniform(0,1) distance = x**2 +
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
result = estimate_pi(n)
print (result)
随机导入
def估算值_pi(n):
数值\点\圆=0
总点数=0
对于范围内的u(n):
x=随机均匀(0,1)
y=随机均匀(0,1)
距离=x**2+y**2
如果python的输入函数是一个字符串,而您的代码需要一个整数。只需将n转换为整数,就可以了
n = int(input("Enter A Random Number"))
您必须将输入从string
转换为int
:estimate\u pi(int(n))
正确的代码是:
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
result = estimate_pi(int(n))
print (result)
随机导入
def估算值_pi(n):
数值\点\圆=0
总点数=0
对于范围内的u(n):
x=随机均匀(0,1)
y=随机均匀(0,1)
距离=x**2+y**2
如果距离必须将输入类型转换为整数:
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
n = int(n) #converting n from string to integer
result = estimate_pi(n)
print (result)
随机导入
def估算值_pi(n):
数值\点\圆=0
总点数=0
对于范围内的u(n):
x=随机均匀(0,1)
y=随机均匀(0,1)
距离=x**2+y**2
如果距离我猜,您是在询问在“def”块中使用“input()”方法
我试了以下方法,效果很好
让我知道你到底犯了什么错误
def estimate_pi():
n =int input("Enter A Random Number")
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
result = estimate_pi()
print (result)
def估算值_pi():
n=整数输入(“输入随机数”)
数值\点\圆=0
总点数=0
对于范围内的u(n):
x=随机均匀(0,1)
y=随机均匀(0,1)
距离=x**2+y**2
如果距离