随机数相加等于固定值_excel随机函数出来的数相加等于一个想要的固定值

匿名用户

1级

2014-09-17 回答

Option Explicit

Function getRandom(total As Integer, max As Integer, num As Integer) As Boolean

'total是最后要得到的总和,max是最大不能超过的数,num是产生多少个随机数

Dim ranNum As Single '随机数

Dim leftNum As Single '剩余数

Dim conNumTotal As Single '确定的剩余数

Dim i As Integer

'判断条件是否满足

getRandom = True

If max * num < total Then

'根本就不可能满足条件,直接退出

getRandom = False

Exit Function

End If

conNumTotal = 0

For i = 1 To num - 1 Step 1

DoEvents

Randomize '随机化

'很显然地所有的ranNum都满足小于max的条件

ranNum = Rnd() * max '产生随机数

'判断当前数据的合理性

leftNum = total - conNumTotal - ranNum

If max * (num - i) < leftNum Then

'无法满足基本要求,退回序列

i = i - 1

Else

'满足要求,继续

conNumTotal = conNumTotal + ranNum

Debug.Print ranNum

End If

'自行处理产生的ranNum

Next i

'最后一个随机数

ranNum = total - conNumTotal

Debug.Print ranNum

debug.print "over"

'由于最后一个数

End Function

Sub a()

getRandom 200, 11, 20

End Sub

这样可以么?

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值