如何可视化这些未出现的数字.(C++)

How to visualize these numbers that are not appearing. (C++)

本文关键字:数字 C++ 可视化      更新时间:2023-10-16

我有一个练习,用于我的编程入门课,我对此有疑问(代码将在这里(。任务非常简单,只需合并两个数组并按升序对它们进行排序。现在,我把所有东西都放下了,但是当我运行代码时,其中两个数字不可见(最后两个(。完整程序的代码如下。

#include <iostream>
using namespace std;
void mergeSortedArrays(const int array1[], int size1, const int array2[], int size2, int result[])
{
    int tmp;
    bool swap;
    int sizefull = size1 + size2;
    int loops = 0;
    while (loops < size1)
    {
        result[loops] = array1[loops];
        loops++;
    }
    while (loops < sizefull)
    {
        result[loops] = array2[loops];
        loops++;
    }
    do {
        swap = false;
        for (int i = 0; i < sizefull - 1; i++)
        {
            if (result[i] > result[i + 1])
            {
                tmp = result[i + 1];
                result[i + 1] = result[i];
                result[i] = tmp;
                swap = true;
            }
        }
    } while (swap);
}

int main()
{
    const int SIZE1 = 3, SIZE2 = 4;
    const int sizefull = SIZE1 + SIZE2;
    int array1[SIZE1] = { 3, 8, 9 };
    int array2[SIZE2] = { -7, -2, 0, 7 };
    int result[sizefull];
    mergeSortedArrays(array1, SIZE1, array2, SIZE2, result);
    for (int i = 0; i < sizefull; i++)
    {
        cout << result[i] << " ";
    }
    cout << endl;
    return 0;
}

单击此处查看程序显示的内容。我只是想知道顶部的"mergeSortedArrays"函数是否有任何问题,可能是在我将值插入"结果"数组的部分。感谢大家的帮助或伸出援手。:)

代码在"mergeSortedArrays"函数中存在问题。

您的第二个循环(mergeSortedArrays while(:

while (loops < sizefull)
{
    result[loops] = array2[loops];
    loops++;
}

使用错误的索引进行array2,即 array2只有size2个项目,但您使用最多可以sizefull - 1的计数器oops

我的建议是再添加一个计数器,例如:

int cnt = 0;
while (loops < sizefull)
{
    result[loops] = array2[cnt++];
    loops++;
}

或者改用for

for (int cnt = 0; loops < sizefull; cnt++)
{
    result[loops] = array2[cnt];
    loops++;
}