本人刚接触c#没几天,写了一个控制台程序 ,想要给一个长度为13的数组赋值,要求数组的值是从0到52的任意的不重复的13个数,于是写了一下代码,可是提示出错,希望大家帮帮小弟
using System;namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
int[] a= new int[13];
int i ,temp, j=0;
public void Function()
{
for (;j<12;j++)
{
Random ra = new Random();
temp=ra.Next(0,52);
for(i=0;i<12;i++)
{
if (temp==a[i])
{
Function();
}
}
a[j]=temp;
}
for (int x=0;x<13;x++)
{
Console.WriteLine(a[x]);
}
}
[STAThread]
static void Main(string[] args)
{
Class1 c1 = new Class1();
c1.Function();
Console.Read();
}
}
}
using System;namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
int[] a= new int[13];
int i ,temp, j=0;
public void Function()
{
for (;j<12;j++)
{
Random ra = new Random();
temp=ra.Next(0,52);
for(i=0;i<12;i++)
{
if (temp==a[i])
{
Function();
}
}
a[j]=temp;
}
for (int x=0;x<13;x++)
{
Console.WriteLine(a[x]);
}
}
[STAThread]
static void Main(string[] args)
{
Class1 c1 = new Class1();
c1.Function();
Console.Read();
}
}
}
能不能这样考虑:设一个布尔数组a[53],初始值为false。
然后用Random()生成(0,52)随机数,每生成一个数将与数组a的下标对应的元素的值赋为true,然后传给int数组b[13]。
部分代码是这样:
int count = 0, i = 0, temp = 0; //count表示置数的次数
int[] b = new int[13];
boolean[] a = new boolean[53];
While(count<=13)
{
Random ra = new Random();
temp = ra.Next(0,52);
if(a[temp] == false)
{
a[temp] = true;
b[i] = temp;
i++;
count++;
}
else
{
continue;
}
}
{
static void Main(string[] args)
{
int [] a = new int[52];
for (int i = 0; i < a.Length; i++)
{
a[i] = i + 1;
} int[] b = new int[13]; Random r = new Random(unchecked((int)DateTime.Now.Ticks)); int var;
for (int i = 52; i > 39; i--)
{
int temp = r.Next(0, i);
b[52 - i ] = a[temp]; var = a[i - 1];
a[i - 1] = a[temp];
a[temp] = var;
} foreach (int temp in b)
{
Console.Write(temp + " ");
}
}
}
开始2个值一样
扫描第1个array记下数字出现次数 如果多余1次就再第2个array里面把这个删除
using System;class Demo
{
static void Main(string[] args)
{
int [] a = new int[52];
for (int i = 0; i < a.Length; i++)
{
a[i] = i + 1;
} int[] b = new int[13]; Random r = new Random(unchecked((int)DateTime.Now.Ticks)); int var;
for (int i = 52; i > 39; i--)
{
int temp = r.Next(0, i);
b[52 - i ] = a[temp]; var = a[i - 1];
a[i - 1] = a[temp];
a[temp] = var;
} foreach (int temp in b)
{
Console.Write(temp + " ");
}
}
}
int i ,temp, j=0;
public void Function()
{
for (;j <12;j++)
{
Random ra = new Random();
temp=ra.Next(0,52);
for(i=0;i <12;i++)
{
if (temp==a[i]) //无值怎么==?
{
Function();
}
}