Random在for循环中返回相同的值

时间:2017-03-14 23:07:05

标签: c++ for-loop visual-c++ vector random

我已将代码缩减到最小,并且编译再现相同的错误。我知道它会发出警告,你不需要提及它们。我对编码很新,所以我很感激帮助。     我遇到的问题是向量Xpos和Ypos在main()中每次完成for循环时都返回相同的值。我得到一个rnadom输出,但所有向量值都重复。他们应该是不同的。你能帮我找到什么问题吗?非常感谢。代码:

#include "stdafx.h"
#include <ctime>
#include <cmath>
#include <random>
#include <iostream>

using namespace std;


//error is here?

int phaseTwoSimulate(double &Xpos, double &Ypos, int diameter, double stepSize) {


    while (pow(Xpos - 201, 2) + pow(Ypos - 201, 2) < pow(diameter, 2)) { 
// while inside cicle

        int direction = rand() % 4;
        switch (direction) {
        case 0://north
            Ypos = Ypos - stepSize;
            break;
        case 1://east
            Xpos = Xpos + stepSize;
            break;
        case 2://south
            Ypos = Ypos + stepSize;
            break;
        case 3://west
            Xpos = Xpos - stepSize;
            break;
        }
    }
    return 0;
}

int main()
{
    double Xpos = 201;
    double Ypos = 201;
    srand(time(NULL));
    for (int x = 0; x < 50; x++) {
        phaseTwoSimulate(Xpos,Ypos,50,1);
        cout << Xpos << "," << Ypos << endl;
        double Xpos = 201;
        double Ypos = 201;
    }
    cin.ignore();
    cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您的问题在于此代码中间的两行:

    cout << Xpos << "," << Ypos << endl;
    double Xpos = 201;
    double Ypos = 201;
}

这样做是声明两个变量XposYpos并将它们设置为201.不使用这些变量。当您的循环再次出现时,下一次调用phaseTwoSimulate会使用XposYpos的旧变量(以及旧值),这意味着该点已经在您的圈子之外了函数中的循环立即停止。

要解决此问题,只需将其更改为:

    cout << Xpos << "," << Ypos << endl;
    Xpos = 201;
    Ypos = 201;
}

或者更好的是,将变量移动到更接近它们的位置并将代码更改为

int main()
{
    vector <int> vectorX;
    vector <int> vectorY;
    srand(time(NULL));
    for (int x = 0; x < 50; x++) {
        double Xpos = 201;
        double Ypos = 201;
        phaseTwoSimulate(Xpos, Ypos, 50, 1);
        cout << Xpos << "," << Ypos << endl;
    }
    cin.ignore();
    cin.get();
    return 0;
}