我目前正在使用计算器,但我的 2 个算法无法正常工作。
在我的历史记录(列表框)中,我从计算器中获取数字,我有一个底部可以找到最小的数字。我的代码出错。
我想要一个 [排序] 底部来对数字进行升序或降序排序。我试过 listbox1.sorted 这样的东西,但我只能让它按字母顺序工作。
如果您知道我在 nr.1 上做错了什么或知道如何修复排序算法,请告诉我。
int count = 0;
int tal = 0;
double Mtal = 999999999999999999;
bool hit;
int count1 = 0;
private void button26_Click(object sender, EventArgs e)
{
while (count < 100)
{
foreach (var Listboxitem in listBox1.Items)
{
hit = false;
if (Convert.ToDouble(Listboxitem) < Mtal)
{
Mtal = Convert.ToDouble(Listboxitem);
hit = true;
}
count = count + 1;
if (hit)
{
count1 = count;
}
}
}
this.listBox1.SelectedIndex = count1 - 1;
}
您在 ListBox 中的值是整数。因此,将变量的声明Mtal
从更改double
为int
。然后,而不是Convert.ToDouble()
使用int.Parse()
,因为您需要整数来与现有的最小值进行比较。这样的事情应该适合你:
int count = 0;
int tal = 0;
int Mtal = int.MaxValue;
bool hit;
int count1 = 0;
private void button26_Click(object sender, EventArgs e)
{
while (count < 100)
{
foreach (var Listboxitem in listBox1.Items)
{
hit = false;
if (int.Parse(Listboxitem.ToString()) < Mtal)
{
Mtal = int.Parse(Listboxitem.ToString());
hit = true;
}
count = count + 1;
if (hit)
{
count1 = count;
}
}
}
this.listBox1.SelectedIndex = count1 - 1;
}
然后对于订购,我建议您在List<ListItem>
. 对于您的示例:
private void button_OrderByDescencing_Click(object sender, EventArgs e)
{
List<ListItem> items= new List<ListItem>();
foreach (ListItem a in lb.Items)
{
items.Add(a);
}
items=items.OrderByDescending(a => int.Parse(a.Value)).ToList();
foreach (ListItem a in items)
{
listBox1.Items.Add(a);
}
}
对于升序:
private void button_OrderByAscending_Click(object sender, EventArgs e)
{
List<ListItem> items= new List<ListItem>();
foreach (ListItem a in lb.Items)
{
items.Add(a);
}
items= items.OrderBy(a => int.Parse(a.Value)).ToList();
foreach (ListItem a in items)
{
listBox1.Items.Add(a);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句