[英]Random Sequence Generator in C#
我想在C#中構建一個序列隨機化器移動應用程序。 我想從兩個不同的文本框中檢索一個間隔中的最小和最大數字,然后單擊“生成”按鈕以在新文本框中顯示所有數字的隨機序列。
我的代碼僅顯示一個數字。 它出什么問題了?
謝謝。
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
int seed = 345;
var result = "";
int min = Convert.ToInt32(textBox.Text);
int max = Convert.ToInt32(textBox2.Text);
Random r3 = new Random(seed);
for (int i = min; i < max; i++)
{
ecran.Text = (/*"," + r3.Next(min, max)*/i).ToString();
}
}
為了闡明您的解決方案出了什么問題:
在循環內部,您一直在重新分配ecran.Text的值。
即
1st loop cycle > ecran.Text = ", " + 77
2nd loop cycle > ecran.Text = ", " + 89
//Value of ecran.Text after 1st cycle is ", 77"
//Value of ecran.Text after 2nd cycle is ", 89"
每次迭代都覆蓋ecran.Text的值。
通過在等號ecran.Text += ", " + LOGIC
前面添加加號來解決。 ecran.Text += ", " + LOGIC
發生這種情況是因為您在循環ecran.Text
序列值分配給ecran.Text
。 相反,您應該創建序列的字符串表示形式,並在最后分配它。
通過以下問答使用Shuffle<T>
方法:
int min = Convert.ToInt32(textBox.Text);
int max = Convert.ToInt32(textBox2.Text);
if (max < min) return;
var sequence = Enumerable.Range(min, max-min+1).ToList();
Shuffle(sequence);
ecran.Text = string.Join(",", sequence);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.