c++ For循环算法
C++ For loop algorithm
我是c++的新手,我需要一些帮助,在我的doubleUp函数中的for循环算法。doubleUp函数的目的是,如果数组具有相同的连续值,则每个数字将被加倍。一个例子是,如果一个数组有元素4,4,4和4。通过使用doubleUp函数,新的数组将是8,8,8,8。再次感谢大家!: D
#include <iostream>
using namespace std;
void collectScores(double scores[], int SIZE);
void printScores(double scores[], int stopPlace);
void doubleUp(double scores[], int SIZE);
void collectScores(double scores[], int SIZE)
{
for (int n = 0; n < SIZE; n++)
{
cout << "Please enter a value for element " << (n) << " : ";
cin >> scores[n];
}
cout << endl;
}
void printScores(double scores[], int stopPlace)
{
for (int n = 0; n < stopPlace; n++)
{
cout << "The value of element " << (n) << " : " << scores[n] << endl;
}
}
void doubleUp(double scores[], int SIZE)
{
for (int n = 0; n < SIZE; n++)
{
if (scores[n] == scores[n + 1])
{
scores[n] *= 2;
}
}
}
int main()
{
double r;
const int SIZE = 4;
double scores[SIZE];
collectScores(scores, SIZE);
printScores(scores, SIZE);
cout << endl;
doubleUp(scores, SIZE);
printScores(scores, SIZE);
system("pause");
return 0;
}
除了你在最后错过了一个边缘情况之外,还有一个更大的问题。由于您是在一个方向上向前看,对于双精度对象,这意味着您将错过对的每个岛的相邻相等数字的最后一个元素进行加倍。在下面的代码中,我添加了一个名为isDouble
的状态变量来解决这个问题。
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];
}
正如人们指出的那样,代码中的错误是最后一个元素没有被加倍。这是因为对于数组中的最后一个元素,没有后续元素,这就是代码中"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;
}
}
}
我认为你的doubleUp函数应该稍微修改一下:
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++;
}
}
}
}
添加的部分实际上允许数组中的最后一项被加倍,而原始代码不允许(数组中最后一项之后没有n+1索引)
相关文章:
- C++:尝试使用等效的 STL 算法消除原始循环
- 如何在贝尔曼福特算法中检测负循环?
- 循环中的循环算法
- 有没有一种方法可以使用弗洛伊德-沃歇尔算法给出最短路径,其中存在负权重循环而不允许重叠边缘?
- 使用 while 循环和搜索算法进行复制
- C++ 循环和搜索算法,重复
- STL算法并嵌套以循环
- 使用 c++17 算法并行化简单循环
- 为什么当我使用std::算法而不是纯循环时,这个代码会变慢
- for_each算法在boost::multi_array上循环
- C++循环算法不正确(或文件处理问题)
- 虽然循环/算法问题c ++ visual studio 2012
- C++循环算法逻辑问题
- 如何使用std算法来替换for循环
- 嵌套 for 循环的任何快速搜索算法
- 如何替换我的"for"循环以通过 STL mimax 算法找到最小值/最大值
- 在循环双向链表的第一个节点之前/之后插入的算法是什么?
- 算法循环组合
- 用于枚举完整图的哈密顿循环的算法(循环、反向、环绕或重复不计算在内的排列)
- c++算法循环并行处理