![](/img/trans.png)
[英]I'm getting “undefined reference” errors for a bunch of my functions and I can't figure out why
[英]I can't figure out why my random numbers I'm generating are not storing correctly
我正在編寫一個程序,該程序針對某人輸入的一定數量的數字生成隨機的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];
mounds和1代表元素的數量,而不是數組中的最后一個索引。
cout <<"You just generated a y of: " << moundArray [i][1] << endl;
上面您在第二個字段中使用1作為索引,這意味着該數組在該維度中至少有兩(2)個元素。
我很驚訝您沒有在執行時崩潰。 這行應該是您的問題:
int moundArray [mounds][1];
如果第二個索引的大小僅為[1],則元素[0]是唯一要訪問的有效元素。 嘗試將其增加到2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.