Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用循环的数组_C++_Arrays - Fatal编程技术网

C++ 使用循环的数组

C++ 使用循环的数组,c++,arrays,C++,Arrays,我正在使用代码块上的for循环编写一个数组。代码正在运行,但最终结果与预期不完全相同 我试图改变循环的极限,但没有任何效果。每次程序的最后一行的行为都与其他行不同 #include <iostream> using namespace std; int main() { int testarray[15]; for(int x=0; x<16; x++){ testarray[x] = x*10; cout << x <

我正在使用代码块上的for循环编写一个数组。代码正在运行,但最终结果与预期不完全相同

我试图改变循环的极限,但没有任何效果。每次程序的最后一行的行为都与其他行不同

#include <iostream>

using namespace std;

int main()
{
    int testarray[15];

    for(int x=0; x<16; x++){
      testarray[x] = x*10;
    cout << x << "--" << testarray[x] << endl;
}
}
#包括
使用名称空间std;
int main()
{
int testarray[15];

对于(int x=0;x您在数组
索引时出错。通常数组的索引从
0
n-1

如果,
int testarray[15];

然后我们可以使用
testarray[0]
testarray[14]
。而不是
testarray[15]
。 在代码中,您使用的是
testarray[15]

正确代码:

#include <iostream>

using namespace std;

int main()
{
    int testarray[15];

    for(int x=0; x<15; x++){    // Notice that, i am using 15 here, not 16
      testarray[x] = x*10;
      cout << x << "--" << testarray[x] << endl;
   }
}
#包括
使用名称空间std;
int main()
{
int testarray[15];

对于(int x=0;x)像这样编写数组和循环,
int array[N];对于(int i=0;i
N在这两种情况下都是相同的数字。