c++ - 我不明白为什么我生成的随机数没有正确存储

标签 c++ arrays random

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

关于c++ - 我不明白为什么我生成的随机数没有正确存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111848/

相关文章:

c++ - 在 heapsort 程序中出现 sigabrt 错误

c - 以指针为参数的数组函数

c++ - 为git存储库制作一个c文件

c - 如何实现位数组?

Java线程随机

ios - 随机颜色变化时崩溃

c++ - C++ 中字符串类型的二维数组;

c++ - 如何避免通用函数模板中的额外拷贝?

c++ - 在类外将部分指定的模板化矩阵乘法运算符重载函数声明为友元

java - 在 Groovy 中将可变长度字符串散列为 12 位数字的一种方法函数