gpt4 book ai didi

c++ - 如何可视化这些没有出现的数字。 (C++)

转载 作者:行者123 更新时间:2023-11-28 05:06:23 25 4
gpt4 key购买 nike

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

#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;
}

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

最佳答案

代码在“mergeSortedArrays”函数中有问题。

你的第二个循环(while in mergeSortedArrays):

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

array2 使用了错误的索引,即 array2 只有 size2 项,但是你使用了计数器 oops最大可达 sizefull - 1

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

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

或者使用 for 代替:

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

关于c++ - 如何可视化这些没有出现的数字。 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44643693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com