Random number = new Random();
int n;
for (int counter = 0; counter < 100; counter++)
{
n = number.Next(0,1000);
Console.WriteLine(n);
}
我需要弄清楚如何返回随机数的范围、最大值和最小值。我不允许使用数组。您能否也解释一下您是如何得到答案的。
Random number = new Random();
int n;
for (int counter = 0; counter < 100; counter++)
{
n = number.Next(0,1000);
Console.WriteLine(n);
}
我需要弄清楚如何返回随机数的范围、最大值和最小值。我不允许使用数组。您能否也解释一下您是如何得到答案的。
Random number = new Random();
int min = int.MaxValue,
max = int.MinValue;
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0, 1000);
Console.WriteLine(n);
if (n < min)
min = n;
if (n > max)
max = n;
}
int range = min - max + 1;
Console.WriteLine("Min = {0}, Max = {1}, Range = {2}", min, max, range);
你可以得到所有关于它的 OO 和 Linqy。首先,构建您的累加器类:
class Accumulator
{
public Accumulator Add( int n )
{
min = min.HasValue && min.Value < n ? min.Value : n ;
max = max.HasValue && max.Value > n ? max.Value : n ;
return this ;
}
private int? min = null ;
private int? max = null ;
public int Min { get { return min.Value ; } }
public int Max { get { return max.Value ; } }
public int Range { get { return (Max-Min)+1 ; } }
public override string ToString()
{
return string.Format( "Min:{0}, Max:{1}, Range:{2}" , Min , Max , Range ) ;
}
}
然后是一个简单的咒语:
Random random = new Random() ;
Accumulator summary = Enumerable.Range( 1 , 100 )
.Aggregate( new Accumulator() ,
(acc,n) => acc.Add(random.Next(0,1000))
) ;
Console.WriteLine( summary ) ;
这相当简单,只需跟踪每一步的最小值和最大值:
Random number = new Random();
int min = int.MaxValue, max = int.MinValue;
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0,1000);
min = Math.Min(min, n);
max = Math.Max(max, n);
}
Console.WriteLine(min);
Console.WriteLine(max);
Random number = new Random();
int n;
int min=1000;
int max=0;
for (int counter = 0; counter < 100; counter++)
{
n= number.Next(0,1000);
if (n>max)
{
max=n;
}
if (n<min)
{
min=n;
}
Console.WriteLine(n);
}
Console.WriteLine("max:"+max);
Console.WriteLine("min:"+min);