现在要随机生成一组RGB值,如:#FFFFFF
要点是随机生成6个字符,这6个字符从0-9,A-F中取.然后与#连接构成颜色值.
要点是随机生成6个字符,这6个字符从0-9,A-F中取.然后与#连接构成颜色值.
public static string CreateRandomColor()
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for(int i = 0; i < 6; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(15);
if(temp == t)
{
return CreateRandomColor();
}
temp = t;
randomCode += allCharArray[t];
}
return "#"+randomCode;
}
for(int i = 0; i < 6; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(15);
if(temp == t)
{
return CreateRandomColor();
}
temp = t;
randomCode += allCharArray[t];
}
return "#"+randomCode;
}
调试:
正确,
循环10次
for(int i=0;i<=10;i++)
{
Console.WriteLine(CreateRandomColor());
}
{
Console.WriteLine(CreateRandomColor());
}
却重复了,根本没有达到随机的效果。怎么回事?![](/CuteSoft_Client/CuteEditor/images/emangry.gif)
![](/CuteSoft_Client/CuteEditor/images/emangry.gif)
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
string str1 = CreateRandomColor();
string str2;
for(int i=0;i<=10;i++)
{
str2 = CreateRandomColor();
if(str2!=str1)
{
Console.WriteLine(str2);
str2=str1;
}
}
}
public static string CreateRandomColor()
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for(int i = 0; i < 6; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(15);
if(temp == t)
{
return CreateRandomColor();
}
temp = t;
randomCode += allCharArray[t];
}
return "#"+randomCode;
}
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
string str1 = CreateRandomColor();
string str2;
for(int i=0;i<=10;i++)
{
str2 = CreateRandomColor();
if(str2!=str1)
{
Console.WriteLine(str2);
str2=str1;
}
}
}
public static string CreateRandomColor()
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for(int i = 0; i < 6; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(15);
if(temp == t)
{
return CreateRandomColor();
}
temp = t;
randomCode += allCharArray[t];
}
return "#"+randomCode;
}