2017-04-19 45 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