2016-12-05 66 views
0

我想分割兩個不同文本框中的兩個值,並將結果顯示在第三個文本框中。這裏是我的代碼至今:劃分文本框中的值,並在第三個文本框中生成值

private void Divide() 
{ 
    int val1, val2; 
    if (!string.IsNullOrEmpty(mergeSortTime.Text) && !string.IsNullOrEmpty(selectionSortTime.Text)) 
    { 
    int.TryParse(mergeSortTime.Text, out val1); 
    int.TryParse(selectionSortTime.Text, out val2); 
    resetTimeDisplay.Text = (val1/val2).ToString(); 
    } 
} 

和我所說的方法在這裏:

private void selectionSortButton_Click(object sender, EventArgs e) 
{ 

    selectionSortButton.Enabled = false; 
    button1.Location = resetButton.Location; 
    button1.Visible = true; 
    InitializeForm(); 
    sw.Start(); 
    bgWorker.RunWorkerAsync(); 
    while (bgWorker.IsBusy) 
    Application.DoEvents(); 
    idList.SelectionSort(); 
    if (!bgWorkCancelled) 
    DisplayIDList(displayDGV); 
    sw.Stop(); 
    TimeSpan ts = sw.Elapsed; 
    string elapsedTime = String.Format("{0:0}" + "." + "{1:0}",ts.Seconds, ts.Milliseconds); 
    selectionSortTime.Text = elapsedTime; 
    mergeSortButton.Enabled = false; 
    quickSortButton.Enabled = false; 
    resetButton.Location = button1.Location; 
    button1.Visible = false; 
    resetButton.Visible = true; 
    Divide(); 
} 

它是如何工作的,現在是我輸入一個數字,一個完全獨立的文本框和生成的列表無序的價值。然後,我有2個按鈕,使用2種不同的排序方式,在它們旁邊,我有一個顯示屏,顯示排序值需要多長時間。我需要劃分的2個顯示值。它給了我一個錯誤,說:「試圖除以零」,我試着調試代碼,看到val1和val2都有一個值0,所以錯誤顯然是正確的?但mergeSortTime.TextselectionSortTime.Text都具有正確的值。

任何人都介意分享一些見解?

謝謝!

回答

0

你真正想要做的是:

private void Divide() 
{ 
    double val1 = 0.0; 
    double val2 = 0.0; 
    double reset = 0.0; 
    if (!string.IsNullOrEmpty(mergeSortTime.Text) && !string.IsNullOrEmpty(selectionSortTime.Text)) 
    { 
     //Assuming the value entered on the textboxes are numeric the second textbox is greater than 0. 
     val1 = double.Parse(mergeSortTime.Text); 
     val2 = double.Parse(selectionSortTime.Text); 
     //To make sure that val2 is not equal to 0 before the calculation 
     if(val2 != 0) 
    { 
    reset = val1/val2; 
    resetTimeDisplay.Text = reset.ToString(); 
    } 
    } 
} 
+0

好。我只是將我的代碼切換到上面,並且出現了錯誤:「int.Parse(mergeSortTime.Text)中的輸入字符串格式不正確」我相信我在其他方法上遇到了同樣的錯誤拍攝。 – Luke

+0

我也很感謝你給我的幫助! – Luke

+0

您收到此錯誤的可能原因是因爲您在一個或所有文本框中輸入了非數字值。確保你只輸入數字值。還要確保您在第二個文本框中輸入的值不等於0.否則,您將收到一個0除法異常。 – Auguste

相關問題