我是建设一个名为myIntArray数组,它被初始化在构造函数中的所有787-9的一类。我然后建立了一个称为printArray(int y)对功能用于打印每行y个阵列。我的问题是,它打印数组的最后10个元素为0时,他们应该是所有9。任何一个可以告诉我为什么?
class MyList
{
public:
MyList();
void printArray(int y);
private:
const static int ARRAY_SIZE{1000};
int myIntArray[ARRAY_SIZE];
};
void MyList::printArray(int y)
{
for(int row{0}; row < ARRAY_SIZE; ++row)
{
for(int col{0}; col < y; ++col)
{
std::cout << myIntArray[row] << " ";
++row;
}
std::cout << '\n';
}
}
您试图访问的许多元素过去的数组的末尾,正如有人已经评论。第二回路是冗余的。考虑使用商余“%”。
for(int row{0}; row < ARRAY_SIZE; ++row) {
std::cout << myIntArray[row];
if (!((row+1) % y) ) {
std::cout << '\n';
}
}
你printArray功能是怪异。所以你会错过一些,因为递增连续两次的元素,您递增外环和内环行变量。要知道,你也可以伸手的根据y的价值债券。