【发布时间】:2018-11-15 05:13:05
【问题描述】:
我是 C++ 新手,正在使用 C++98 进行作业。我正在尝试使用指向数组的指针遍历对象数组。
它正在正确打印第一个点,然后是一些值。
这里是sn-ps的代码:
struct Point { int x, y; };
int randomNumber(int low, int high ) {
int randomNumber = low + (rand())/ (RAND_MAX/(high-low));
cout << setprecision(2);
return randomNumber;
}
Point *generateCoordinates(int nodesPerBlock) {
Point cities[nodesPerBlock];
for (int i = 0; i < nodesPerBlock; i++) {
cities[i].x = randomNumber(1, 50);
cities[i].y = randomNumber(1, 50);
}
return cities;
}
int main() {
int nodesPerBlock = 5;
Point *points = generateCoordinates(nodesPerBlock);
for (int n = 0; n < (nodesPerBlock-2); n++) {
cout << "n: x=" << points[n].x << ", y=" << points[n].y << endl;
cout << "n+1: x=" << points[n+1].x << ", y=" << points[n+1].y << endl;
}
}
打印出来:
n: x=1, y=4
n+1: x=18, y=11
n: x=2049417976, y=32767
n+1: x=2049417976, y=32767
n: x=2049417976, y=32767
n+1: x=2049417984, y=167804927
而实际打印的分数是:
Point : x=1, y=4.
Point : x=18, y=11.
Point : x=13, y=6.
Point : x=2, y=16.
Point : x=16, y=22.
转介this questions和this,但目前没有成功。
【问题讨论】:
-
请参阅stackoverflow.com/questions/7769998/…,但对接受的答案持保留态度。