【发布时间】:2015-01-27 02:54:30
【问题描述】:
我不确定为什么这个循环不会一直运行。我正在学习 c++,这也是我第一次使用指针。任何反馈表示赞赏。该程序的目标是取两个随机数 0-200,取其差,并将其添加到向量中。然后得到每个数与新数的差值,以此类推,直到没有更多正的可能性。
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<vector>
#include<algorithm>
int main(int argc, const char * argv[]) {
using namespace std;
int m,n; //Two random numbers between 1 and 200
vector<int> board;
vector<int>::iterator it;
srand(time(NULL));
m = rand() % 201;
n = rand() % 201;
board.insert(board.begin(), m);
board.insert(board.begin(), n);
cout << "\nThe two numbers are " << m << " and " << n << endl;
for(it=board.begin(); it != board.end(); it++){
for(vector<int>::iterator j = board.begin(); j != board.end(); j++){
int a = *j - *it;
if (a > 0) { //Is non-negative
if (find(board.begin(), board.end(), a) != board.end()) {
board.insert(board.end(), a);
}
}
}
for (it=board.begin(); it<board.end(); it++) {
cout << ' ' << *it;
cout << ' ';
}
return 0;
}
}
【问题讨论】:
标签: c++ pointers for-loop iterator nested-loops