除以文本框中的值并在第3个文本框中生成值

时间:2016-12-05 20:29:34

标签: c#

我正在尝试将两个不同文本框中的两个值分开,并将结果显示在第三个文本框中。这是我到目前为止的代码:

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都具有正确的值。

任何人都在分享一些见解?

谢谢!

1 个答案:

答案 0 :(得分: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();
     }
  }
}