int Foo(int n)
{
int k = 0;
var rand = new Random();
for (var i = 0; i < n; i++)
{
var r = rand.Next(n);
k += (r >= n - 3) ? 2 : ((r >= n - 9) ? 1 : 0);
}
return k;
}上面的 Foo 函数的定义值和值域都是 int 。
很明显:
Foo(-1) = 0
Foo(0) = 0
Foo(1) = 2
Foo(2) = 4
Foo(3) = 6
当 n > 3 时,Foo(n) 的值就不是固定的了。问:
1. Foo(4) 的最大值和最小值是多少?
2. Foo(100000000) 的最大值和最小值是多少?
解决方案 »
- 用C#做个提示的功能
- c# 编写一个将word转换成pdf的工具
- 请教两个问题,一个是DataTable.Rows.Count,一个关于遍历
- 请教各位:我的程序在 Session_End 里调用了Server.Execute("LogOut.aspx") 语句,但为什么没有执行?
- winform滚动条问题
- .vwws文件,里面内容是XML格式的,C#可以解析吗
- public frmChild(cResult r):this() 谁能告诉我:this()是什么意思
- 请问怎么屏蔽mobile 上 webbrowser的右键菜单
- 百思不求其解,怪哉怪哉!
- WinFrom 中的dataGrid为何没有滚动条
- 新手C#小问题
- 求一正则表达式。。?
它返回一个大于或等于零而小于2,147,483,647的数
next(n)
返回一个小于所指定最大值n的正随机数
不错,研究下
Random.Next(int maxValue) 方法返回一个小于所指定最大值的非负随机数。
注意:是非负随机数,而不是正随机数。
这个问题是针对 Microsoft .NET Framework 3.5 SP1 的 Random 类来提问的,该类是一个伪随机数的类,而不是真正的随机数。
如果是真正的随机数,上述问题就要改为 Foo(4) 和 Foo(100000000) 的“数学期望”是多少?注:Microsoft .NET Frmawork 3.5 SP1 的 Random 类的部分代码如下所示:public virtual int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException("maxValue", string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_MustBePositive"), new object[] { "maxValue" }));
}
return (int) (this.Sample() * maxValue);
}protected virtual double Sample()
{
return (this.InternalSample() * 4.6566128752457969E-10);
}private int InternalSample()
{
int inext = this.inext;
int inextp = this.inextp;
if (++inext >= 0x38)
{
inext = 1;
}
if (++inextp >= 0x38)
{
inextp = 1;
}
int num = this.SeedArray[inext] - this.SeedArray[inextp];
if (num < 0)
{
num += 0x7fffffff;
}
this.SeedArray[inext] = num;
this.inext = inext;
this.inextp = inextp;
return num;
}
返回 1至1000之间的随机数
Foo(100000000) 理论上最小值0,最大值2×100000000=200000000由于随机性,Foo(4)应该能够达到最大最小值吧,毕竟就5个值之间随机,不过达到最小值的概率只有1/4。Foo(100000000)要达到那个最大值几乎不可能,但毕竟理论上还是有这个几率的,几率为3/100000000。相比之下,最小值出现概率大多了,由于统计较麻烦,不作要求的话我就不去统计了。
Foo(100000000)的最大值和最小值则要分析伪随机数的生成方法了。