我正在制作一个程序,为某人输入的数字生成一个随机的x和y点。由于某种原因,我的随机数字没有存储在数组中。我在生成点的循环中输出数组,在for循环中输出结束,y坐标不相同:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned)time(0));
int mounds =0;
//prompt for number of mounds, uncertainty, and number of sites
cout <<"Please enter the number of mounds at the site: ";
cin >> mounds;
//declaration of an array that will hold the x and y for each mound
int moundArray [mounds][1];
for(int i =0; i < mounds; i++)
{
//generate a random x
moundArray [i][0] = rand()%1331;
cout <<"You just generated an x of: " << moundArray [i][0] << endl;
//sleep(1);
//generate a random y
moundArray [i][1] = rand()%1743;
cout <<"You just generated a y of: " << moundArray [i][1] << endl;
//sleep(1);
}
//for loop to display my results
for(int j =0; j < mounds; j++)
{
cout <<"random x: " << moundArray [j][0] << endl;
cout <<"random y: " << moundArray [j][1] << endl;
}
return 0;
}
答案 0 :(得分:2)
int moundArray [mounds][1];
mounds和1表示元素的数量,而不是数组中的最后一个索引。
cout <<"You just generated a y of: " << moundArray [i][1] << endl;
上面你使用1作为第二个字段中的索引,这意味着该数组在该维度中至少有两(2)个元素。
答案 1 :(得分:2)
我很惊讶你没有因执行而崩溃。这一行应该是你的问题:
int moundArray [mounds][1];
如果第二个索引的大小只有[1],则元素[0]是唯一有效的元素。尝试将其增加到2。