Foxtable(狐表)用户栏目专家坐堂 → [求助]概率问题


  共有39人关注过本帖树形打印复制链接

主题:[求助]概率问题

帅哥哟,离线,有人找我吗?
linyunu1
  1楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:幼狐 帖子:163 积分:1100 威望:0 精华:0 注册:2020/1/16 11:58:00
  发帖心情 Post By:2024/12/21 18:09:00 [显示全部帖子]

Public Sub Main()
	Dim random As New Random()
	Dim items() As String = {"物品1", "物品2", "物品3", "物品4", "物品5", "物品6", "物品7", "物品8", "物品9", "物品10"}
	Dim probabilities() As Double = {0.9, 0.7, 0.5, 0.3, 0.2, 0.15, 0.12, 0.1, 0.08, 0.05}
	' 确保概率之和为1
	Dim totalProbability As Double = probabilities.Sum()
	For i As Integer = 0 To probabilities.Length - 1
		probabilities(i) /= totalProbability
	Next
	' 随机选择物品1000次并输出
	For i As Integer = 1 To 1000
		Dim randValue As Double = random.NextDouble()
		Dim cumulativeProbability As Double = 0
		For j As Integer = 0 To probabilities.Length - 1
			cumulativeProbability += probabilities(j)
			If randValue <= cumulativeProbability Then
				Console.WriteLine("第" & i & "次选中的物品是: " & items(j))
				Exit For
			End If
		Next
	Next
End Sub

这段代码将执行以下步骤:

  1. 初始化一个Random对象用于生成随机数。
  2. 定义物品数组items和对应的概率数组probabilities
  3. 确保概率之和为1,通过将每个概率除以总概率来标准化。
  4. 循环1000次,每次生成一个0到1之间的随机数。
  5. 根据随机数和累积概率选择物品,并输出每次被选中的物品。

 回到顶部