前六个可以任意取,先取出最后一位,然后在取其余六位时相比较,要是七个数字全部相同,则最后一位减一或加一,这样就是不同的七位数了,最后一位如不大于8则加一,等于九则减一。主要代码如下:
using System;
using System.Text;
using System.Windows.Forms;
namespace RandomNum
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private StringBuilder _numSave;
private void button1_Click(object sender, EventArgs e)
{
this._numSave = new StringBuilder();
System.Random random = new Random();
string value = random.Next(10).ToString();//十以内的数字,取值范围0~9
int num=0;//比较相同的次数
for (int i = 0; i < 6; i++)
{
string n = random.Next(10).ToString();//取六个数字
this._numSave.Append(n);
if (n == value)
{
num++;
}
}
if (num == 6)
{
int n = (Int32.Parse(value) == 9) ? Int32.Parse(value) - 1 : Int32.Parse(value) + 1;
this._numSave.Append(n.ToString());
}
else
{
this._numSave.Append(value);
}
this.textBox1.Text = this._numSave.ToString(0, this._numSave.Length);
}
}
}