C++ 使用循环的数组
我正在使用代码块上的for循环编写一个数组。代码正在运行,但最终结果与预期不完全相同 我试图改变循环的极限,但没有任何效果。每次程序的最后一行的行为都与其他行不同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 <
#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在这两种情况下都是相同的数字。