DarkmoonYZW
DarkmoonYZW
2019-09-27 20:56
采纳率: 100%
浏览 328

为什么最终结果有重复?是随机数的问题吗?该如何解决?

为什么最终结果有重复?是随机数的问题吗?该如何解决?

#include
#include
#include
using namespace std;
int main()
{
int Z = 0;
while (Z != 10000)
{
int i = 0,R=0;
int xa = 1, ya = 16, xb = 16, yb = 1;
int Xstep, Ystep;
while (R != 1)
{
i = i + 1;
struct timeb timeSeed;
ftime(&timeSeed);
srand(timeSeed.time * 1000 + timeSeed.millitm); // milli time
unsigned int crand = rand();
Xstep = rand() % 3;
Ystep = rand() % 3;
switch (Xstep)
{
case 0:xa = xa + 1;break;
case 1:xa = xa - 1;break;
case 2:ya = ya + 1;break;
case 3:ya = ya - 1;break;
}
switch (Ystep)
{
case 0:xb = xb + 1;break;
case 1:xb = xb - 1;break;
case 2:yb = yb + 1;break;
case 3:yb = yb - 1;break;
}
switch (xa)
{
case 17:xa = xa - 16;break;
case 0:xa = xa + 16;break;
}
switch (ya)
{
case 17:ya = ya - 16;break;
case 0:ya = ya + 16;break;
}
switch (xb)
{
case 17:xb = xb - 16;break;
case 0:xb = xb + 16;break;
}
switch (yb)
{
case 17:yb = yb - 16;break;
case 0:yb = yb + 16;break;
}
if (xa == xb && ya == yb)
{
R = R + 1;
cout << "运行次数=" << i << endl;
}
}
Z = Z + 1;
}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • hslbloc
    无形有道 2019-09-28 00:06
    已采纳

    有三处错误,分别是:
    1)srand的调用时间间隔太短(程序循环在1毫秒内rand()值完全一样,因此会重复计算,直至1毫秒之后结束该冗余计算过程。症状为程序假死)
    2)Xstep和Ystep的取模运算不正确(case 3永远不执行)
    3)局部变量i的生命周期不正确(假设你说的打印输出i重复是问题)

    解决方案参见以下代码:

    // 解决方案一:将srand函数和局部变量i的声明放在  while (Z != 10000) 循环体之前
    int main()
    {
        int i= 0, Z = 0;
        struct timeb timeSeed;
        ftime(&timeSeed);
        srand(timeSeed.time * 1000 + timeSeed.millitm); // milli time
    
        while (Z != 10000)
        {
            int R=0;
            int xa = 1, ya = 16, xb = 16, yb = 1;
            int Xstep, Ystep;
            while (R != 1)
            {
                i = i + 1;
                unsigned int crand = rand();
    
                Xstep = rand() % 4;
                Ystep = rand() % 4;
    
                // 此处代码省略
                // ...
    
            }
            Z = Z + 1;
        }
    }
    
    

    或者下面代码也可以,但是从效率上不建议这样做(你的循环次数太多,并且也不需要每次循环都使用srand设置种子)

    // 解决方案二:将srand函数的参数加上变量,确保每次循环都不重复
    int main()
    {
        int i= 0, Z = 0;
        while (Z != 10000)
        {
            int R=0;
            int xa = 1, ya = 16, xb = 16, yb = 1;
            int Xstep, Ystep;
            while (R != 1)
            {
                i = i + 1;
                struct timeb timeSeed;
                ftime(&timeSeed);
                srand(timeSeed.time * 1000 + Z * 100 + i * 10 + timeSeed.millitm); // milli time
                unsigned int crand = rand();
    
                Xstep = rand() % 4;
                Ystep = rand() % 4;
    
                // 此处代码省略
                // ...
    
            }
            Z = Z + 1;
        }
    }
    
    点赞 评论

相关推荐