鱼C论坛

 找回密码
 立即注册
查看: 1576|回复: 2

[已解决]我想請問我的程式碼哪裡錯

[复制链接]
发表于 2020-7-26 22:59:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
她顯示 if temp[0] == 1:
IndexError: list index out of range
蒙地卡羅模擬
假設小名站在原點(0, 0),他可以選擇前進、後退、右轉、左轉,機率均為1/4。

計算走了50步,和原點的原點距離是多少?利用迴圈模擬30次,觀察這30次都落在什麼範圍。
import random
import math
site = [0, 0]
temp = [random.randrange(1, 5) for i in range(50)]
n = 0
list1 = []
list1.append(temp)
print(temp)
while len(temp) >= 0:
    if temp[0] == 1:
        site[0] += 1
    elif temp[0] == 2:
        site[0] -= 1
    elif temp[0] == 3:
        site[1] += 1
    else:
        site[1] -= 1
    n += 1
    del temp[0]
    print(site)  
distance = pow(site[0], 2) + pow(site[1], 2)
print(distance)
print(site)
最佳答案
2020-7-26 23:30:14
应该是在不为空的情况下循环。
  1. import random
  2. import math
  3. site = [0, 0]
  4. temp = [random.randrange(1, 5) for i in range(50)]
  5. n = 0
  6. list1 = []
  7. list1.append(temp)
  8. print(temp)
  9. while temp:
  10.     if temp[0] == 1:
  11.         site[0] += 1
  12.     elif temp[0] == 2:
  13.         site[0] -= 1
  14.     elif temp[0] == 3:
  15.         site[1] += 1
  16.     else:
  17.         site[1] -= 1
  18.     n += 1
  19.     del temp[0]
  20.     print(site)  
  21. distance = pow(site[0], 2) + pow(site[1], 2)
  22. print(distance)
  23. print(site)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-7-26 23:30:14 | 显示全部楼层    本楼为最佳答案   
应该是在不为空的情况下循环。
  1. import random
  2. import math
  3. site = [0, 0]
  4. temp = [random.randrange(1, 5) for i in range(50)]
  5. n = 0
  6. list1 = []
  7. list1.append(temp)
  8. print(temp)
  9. while temp:
  10.     if temp[0] == 1:
  11.         site[0] += 1
  12.     elif temp[0] == 2:
  13.         site[0] -= 1
  14.     elif temp[0] == 3:
  15.         site[1] += 1
  16.     else:
  17.         site[1] -= 1
  18.     n += 1
  19.     del temp[0]
  20.     print(site)  
  21. distance = pow(site[0], 2) + pow(site[1], 2)
  22. print(distance)
  23. print(site)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-7-26 23:59:02 | 显示全部楼层
永恒的蓝色梦想 发表于 2020-7-26 23:30
应该是在不为空的情况下循环。

謝謝
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 10:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表