开发者

problem with converting numbers in textBox

The code below belongs to a binary search algorithm. The user enters numbers in textbox1 and enters the number that he want 开发者_运维技巧to find with binarysearch in textbox2. When I enter for example 16 in textBox2 and put breakpoint on the line I commented, I see that the value of searchnum is 10.

I think it converts to hexadecimal. I don't know why. Can you help me?

private void button1_Click(object sender, EventArgs e)
{
    string[] source = textBox1.Text.Split(',');
    int[] nums = new int[source.Length];
    for (int i = 0; i < source.Length; i++)
    {
        nums[i] = Convert.ToInt32(source[i]);
    }

    string str_searchnum = textBox2.Text;
    int searchnum = Convert.ToInt32(str_searchnum); // str_searchnum shows the value 16 but searchnum shows 10
    int first = 0;

    int last = nums.Length - 1;

    while (1 < nums.Length - 1)
    {
        int mid = (int)Math.Floor(first + last / 2.0);

        ////if (first < last)
        ////{
        ////    break;
        ////}

        if (searchnum < nums[mid])
        {
            last = mid - 1;
        }
        if (searchnum > nums[mid])
        {
            first = mid + 1;
        }
        else
        {
            MessageBox.Show(nums[mid].ToString());
        }
    }
}


Check to see if the debugger is set to display values using hexadecimal notation? You can find this option by right clicking in the watch window.

If that's not it, step through the entire method. What is the value of str_searchnum?

Although I personally prefer int.TryParse(), Convert.ToInt32() should be well-tested and not be doing any base conversions.


Why not use Array.BinarySearch? Also, your loop condition is (probably) wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜