C# 生成随机数数组
using System;
using System. Collections. Generic;
using System. Linq;
using System. Text;
using System. Threading. Tasks;
namespace Tools
{
public class randoms
{
private static Random ra = new Random ( unchecked ( ( int ) DateTime. Now. Ticks) ) ;
public static float [ ] RandomFloat ( float minValue, float maxValue, int num)
{
float [ ] arrNum = new float [ num] ;
float tmp = 0 ;
for ( int i = 0 ; i <= num - 1 ; i++ )
{
tmp = GetRandomFloat ( minValue, maxValue) ;
arrNum[ i] = tmp;
}
return arrNum;
}
public static float [ ] RandomFloatGap ( float minValue, float maxValue, int num, double minGap= 0.01 )
{
float [ ] arrNum = new float [ num] ;
float tmp = 0 ;
for ( int i = 0 ; i <= num - 1 ; i++ )
{
int maxRandomTimes = 1000 ;
while ( true )
{
tmp = GetRandomFloat ( minValue, maxValue) ;
if ( IsRepeat ( arrNum, tmp, minGap) == false )
{
arrNum[ i] = tmp;
break ;
}
maxRandomTimes-- ;
if ( maxRandomTimes <= 0 )
break ;
}
}
return arrNum;
}
private static float GetRandomFloat ( float minValue, float maxValue)
{
float result = Convert. ToSingle ( ra. NextDouble ( ) * ( maxValue - minValue) + minValue) ;
return result;
}
private static bool IsRepeat ( float [ ] arrNum, float tmp, double gap = 0.01 )
{
bool bIsHave = false ;
for ( int i = 0 ; i < arrNum. Length; i++ )
{
if ( System. Math. Abs ( arrNum[ i] - tmp) <= gap)
return true ;
}
return bIsHave;
}
}
}
调用
float [ ] point_y = Tools. randoms. RandomFloatGap ( - 15 , 15 , 20 , 0.5 ) ;
foreach ( float temp in point_y)
{
System. Console. WriteLine ( temp. ToString ( ) ) ;
}