我无法弄清楚为什么我生成的随机数没有正确存储

I can't figure out why my random numbers I'm generating are not storing correctly

本文关键字:存储 随机数 弄清楚 为什么      更新时间:2023-10-16

我正在制作一个程序,该程序为某人输入的数字生成随机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;
}

我很惊讶您没有在执行时崩溃。这条线在这里应该是您的问题:

int moundArray [mounds][1];

如果第二个索引的大小为[1],则元素[0]是唯一可以访问的有效元素。尝试将其增加到2。

int moundArray [mounds][1];

土丘和1表示元素数,而不是数组中的最后一个索引。

cout <<"You just generated a y of: " << moundArray [i][1] << endl;

上方您使用1个作为第二个字段中的索引,这意味着该数组在该维度中至少具有两个(2)个元素。