根据问题的定义,“RandNumb (1, 10, 2)”的有效值似乎是:1、3、5、7、9。
在这种情况下。代码如下所示:
class Program
{
static void Main(string[] args)
{
Random rd = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("RandNumb(rd, 1, 10, 2)=" + RandNumb(rd, 1, 10, 2));
Console.WriteLine("RandNumb(rd, 100, 1000, 500)=" + RandNumb(rd, 100, 1000, 500));
Console.WriteLine("RandNumb(rd, 0.001, 0.1, 0.01) =" + RandNumb(rd, 0.001, 0.1, 0.01));
}
Console.ReadLine();
}
public static double RandNumb(Random rd, double min, double max, double step)
{
int range = (int)Math.Floor((max - min) / step);
int stepCount = rd.Next(0, range + 1);
return min + (step * stepCount);
}
}
结果如下所示:
RandNumb(rd, 1, 10, 2)=3
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,071
RandNumb(rd, 1, 10, 2)=5
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,041
RandNumb(rd, 1, 10, 2)=3
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,081
RandNumb(rd, 1, 10, 2)=9
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,011
RandNumb(rd, 1, 10, 2)=7
RandNumb(rd, 100, 1000, 500)=100
RandNumb(rd, 0.001, 0.1, 0.01) =0,091
RandNumb(rd, 1, 10, 2)=5
RandNumb(rd, 100, 1000, 500)=100
RandNumb(rd, 0.001, 0.1, 0.01) =0,001
RandNumb(rd, 1, 10, 2)=1
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,071
RandNumb(rd, 1, 10, 2)=1
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,061
RandNumb(rd, 1, 10, 2)=5
RandNumb(rd, 100, 1000, 500)=100
RandNumb(rd, 0.001, 0.1, 0.01) =0,041
RandNumb(rd, 1, 10, 2)=3
RandNumb(rd, 100, 1000, 500)=600
RandNumb(rd, 0.001, 0.1, 0.01) =0,021