0

私は誰かが入力した数のランダムな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;
}
4

2 に答える 2

2
int moundArray [mounds][1];

mounds と 1 は、配列の最後のインデックスではなく、要素の数を表します。

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

上記では、2 番目のフィールドのインデックスとして 1 を使用しています。これは、配列がその次元に少なくとも 2 つの要素を持っていることを意味します。

于 2012-10-28T18:46:49.933 に答える
2

実行時にクラッシュしていないことに驚いています。ここにあるこの行が問題になるはずです:

int moundArray [mounds][1];

2 番目のインデックスのサイズが [1] しかない場合、要素 [0] はアクセスできる唯一の有効な要素です。それを 2 に増やしてみてください。

于 2012-10-28T18:47:18.467 に答える