Last active
March 30, 2022 07:00
-
-
Save tedliou/9328b8d7a57b8a4a1694 to your computer and use it in GitHub Desktop.
使用Random方法,產生多組亂數值並不重複,存到陣列中,並在控制項中顯示出來。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace Random方法產生亂數不重複範例程式 | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
int[] randomArray = new int[5]; | |
Random rnd = new Random(); //產生亂數初始值 | |
for (int i = 0; i < 5; i++) | |
{ | |
randomArray[i] = rnd.Next(1, 10); //亂數產生,亂數產生的範圍是1~9 | |
for (int j = 0; j < i; j++) | |
{ | |
while (randomArray[j] == randomArray[i]) //檢查是否與前面產生的數值發生重複,如果有就重新產生 | |
{ | |
j = 0; //如有重複,將變數j設為0,再次檢查 (因為還是有重複的可能) | |
randomArray[i] = rnd.Next(1, 10); //重新產生,存回陣列,亂數產生的範圍是1~9 | |
} | |
} | |
} | |
label1.Text = randomArray[0].ToString(); | |
label2.Text = randomArray[1].ToString(); | |
label3.Text = randomArray[2].ToString(); | |
label4.Text = randomArray[3].ToString(); | |
label5.Text = randomArray[4].ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment