2017-04-19 32 views
0

嘿,我目前正在计算器上工作,但我的算法2不能正常工作。 1. 在我的历史(列表框)中,我从计算器中获取数字,然后找到最小的数字。我的代码出错了。 2. 我想有一个[排序]底部排序数字的加入或降序。我试过的东西是listbox1.sorted,但我只是把它作为字母来工作。Windows窗体计算器算法。排序和最高/最低编号

如果你知道自己在做错误的nr.1或知道如何修复排序算法,请让我知道。

int count = 0; 
    int tal = 0; 
    double Mtal = 999999999999999999; 
    bool hit; 
    int cunt = 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) 
       { 
        cunt = count; 
       } 
      } 
     } 
     this.listBox1.SelectedIndex = cunt - 1; 

    } 
+0

无法隐式转换类型 '双' 到 '廉政'。一个明确的转换存在(你是否缺少一个演员?是错误我得到btw –

+0

@EmilSjödin运行你在这里发布的代码我不能重现你的问题,所以.. – EpicKip

回答

1

您在ListBox中的值是整数。因此请将变量Mtal的声明从double更改为int。然后,而不是Convert.ToDouble()使用int.Parse(),因为您需要用于比较现有最小值的整数。 像这样的东西应该为你工作:

int count = 0; 
int tal = 0; 
int Mtal = int.MaxValue; 
bool hit; 
int cunt = 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) 
      { 
       cunt = count; 
      } 
     } 
    } 
    this.listBox1.SelectedIndex = cunt - 1; 

} 

然后对订购我会建议你使用LINQ的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); 
     } 

} 
+0

谢谢你的快速答案@Tadej 1问题我得到(参数1:无法从'object'转换为'string') –

+0

@EmilSjödin请参阅我所做的修改,现在两个问题都应该解决。 – swdev95