C++ C++;For-loop算法
我认为您的双重功能应该稍微编辑一下:C++ C++;For-loop算法,c++,arrays,algorithm,C++,Arrays,Algorithm,我认为您的双重功能应该稍微编辑一下: void doubleUp(double scores[], int SIZE) { for (int n = 0; n < SIZE; n++) { if (n < SIZE-2) { if (scores[n] == scores[n + 1]) { scores[n] *= 2;
void doubleUp(double scores[], int SIZE)
{
for (int n = 0; n < SIZE; n++)
{
if (n < SIZE-2)
{
if (scores[n] == scores[n + 1])
{
scores[n] *= 2;
}
}
else
{
if (scores[n] == scores[n + 1])
{
scores[n] *= 2;
scores[n+1] *= 2;
n++;
}
}
}
}
void doubleUp(双倍分数[],整数大小)
{
对于(int n=0;n
添加的部分本质上允许数组中的最后一项加倍,而原始代码没有这样做(数组中最后一项之后没有n+1索引)除了在结尾处缺少一个边缘情况外,还有一个更大的问题。由于您朝一个方向展望双倍,这意味着您将错过将相邻相等数字的每个孤岛的最后一个元素加倍。在下面的代码中,我添加了一个名为
isDouble
的状态变量,该变量解决了e问题
void doubleUp(double scores[], int SIZE)
{
if (SIZE < 2) return; // 0 or 1 element just return
bool isDouble = false;
for (int n = 1; n < SIZE; n++)
{
if (scores[n] == scores[n - 1])
{
isDouble = true;
scores[n - 1] = 2*scores[n - 1];
}
else if (isDouble)
{
isDouble = false;
scores[n - 1] = 2*scores[n - 1];
}
}
// edge case: possibly double the last element in the array
// if it be identical to the second to last element
if (isDouble) scores[SIZE-1] = 2*scores[SIZE-1];
}
void doubleUp(双倍分数[],整数大小)
{
if(SIZE<2)返回;//0或1元素只返回
bool isDouble=false;
用于(int n=1;n
正如人们指出的,代码中的错误在于最后一个元素没有加倍。这是因为对于数组中的最后一个元素,没有后续元素,这就是代码的“n+1”部分失败的地方。
有很多方法可以解决这个问题。
我使用了两个for循环-一个用于除最后两个元素之外的所有元素,另一个用于最后两个元素
void doubleUp(double scores[], int SIZE)
{
for (int n = 0; n < SIZE-2; n++)
{
if (scores[n] == scores[n + 1])
{
scores[n] *= 2;
}
}
for (int n = SIZE-2; n <SIZE; n++)
{
if (scores[n] == scores[n + 1])
{
scores[n] *= 2;
scores[n+1] *= 2;
}
}
}
void doubleUp(双倍分数[],整数大小)
{
对于(int n=0;n 对于(int n=SIZE-2;n,请解释你的问题和问题。你只说了你想做什么,但没有说你的代码有什么问题。我不必尝试就可以看出:从数组的末尾运行(未定义的行为),你永远不会在一个组中使最后一个加倍。你犯了与OP完全相同的错误,但你犯了两次。