1

这段代码给出了输出,但它有一个问题是当用户在 textbox1 中写入 5,6 和在 textbox3 中写入 7,8 时,它输出 5,6。我知道问题是当数组的元素结束时,它不会打印其余部分其他数组的元素,我评论了问题行。

编辑:我使用 textbox1 和 textbox3 来获取用户想要合并的数组元素

private void button3_Click(object sender, EventArgs e)
{


    string[] source = textBox1.Text.Split(',');
    string[] source1 = textBox3.Text.Split(',');
    int[] nums2 = new int[8];
    int[] nums = new int[source.Length];
    for (int i = 0; i < source.Length; i++)
    {
        nums[i] = Convert.ToInt32(source[i]);

    }
    int[] nums1 = new int[source1.Length];
    for (int j = 0; j < source1.Length; j++)
    {
        nums1[j] = Convert.ToInt32(source1[j]);
    }
    int x = 0;
    int y = 0;
    int z = 0;

    while (x < nums.Length && y < nums1.Length)
    {
        if (nums[x] < nums1[y])
        {
            nums2[z] = nums[x];
            x++;

        }
        else
        {
            nums2[z] = nums1[y];
            y++;
        }

        z++;
    }////----->>it works untill here

    while (x > nums.Length)///this mean when the elements of nums end,out the rest of the elements in other textbox but it doesnt do anything,whats the problem ?
    {
        if (y <= nums1.Length)
        {
            nums2[z] = nums1[y];

            z++;
            y++;
        }
    }
    while (y > nums1.Length)
    {

        if (x <= nums.Length)
        {
            nums2[z] = nums[x];
            z++;
            x++;
        }
    }
        string merge = "";
        foreach (var n in nums2)
            merge += n.ToString() + ",";
        textBox4.Text = merge;


    }
4

2 回答 2

1

你的条件while (x > nums.Length)while (y > nums1.Length)没有意义,因为这永远不会发生。

在前面的块中,只要它们小于or ,您就会递增x和。因此,它们永远不会变大(最多相等),因此两个条件都将始终为假,并且“剩余”项目不会被合并。ynums.Lengthnums1.Length

请注意,您的合并排序实现中还有其他问题,但我猜这不在您的具体问题的范围内。

于 2010-12-18T15:54:21.053 回答
1

做(删除你的最后一段时间)

while (x < nums.Length)
{
        nums2[z] = nums[x];
        z++;
        x++;
}

while (y < nums1.Length)
{
        nums2[z] = nums1[y];
        z++;
        y++;
}

因为您不知道保留了哪些数组项,所以您当前的代码也无法正常工作,因为 y 与 nums 和虎钳 verse 无关。

编辑:我将第一个 while 复制到第二个 while,修复它,删除你的最后一个 while 循环(2 while 和 if 在其中)并替换它。

于 2010-12-18T16:01:20.137 回答