C++新人 遇到一道ACM的题 不知问题出在哪里

问题:在16×16的格子里 一个点在(1,16) 另一个点在(16,1),每次两个点同时随机移动一个单位,方向不限,写出代码,将10000次尝试中两点相遇的步数列出来

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <iostream>
#define random(x) (rand()%x)
using namespace std;
void main()
{
    bool t;
    int j;
    for (int j = 0; j <= 10000; j++)
    {
        t = true;
        for (int k = 0; k <= 10000; k++)
        {
            //模块
            int x;
            srand((int)time(0));
            for (int i = 0; i < 1; i++)
                x = ("%d", random(16) + 1);
            int a, b, m, n;
            a = 1; b = 16; m = 16; n = 1;
            switch (x)
            {
            case 1:b = b + 1; n = n + 1; break;
            case 2:b = b + 1; m = m - 1; break;
            case 3:b = b + 1; m = m + 1; break;
            case 4:b = b + 1; n = n - 1; break;

            case 5:a = a - 1; n = n + 1; break;
            case 6:a = a - 1; m = m - 1; break;
            case 7:a = a - 1; m = m + 1; break;
            case 8:a = a - 1; n = n - 1; break;

            case 9:a = a + 1; n = n + 1; break;
            case 10:a = a + 1; m = m - 1; break;
            case 11:a = a + 1; m = m + 1; break;
            case 12:a = a + 1; n = n - 1; break;

            case 13:b = b - 1; n = n + 1; break;
            case 14:b = b - 1; m = m - 1; break;
            case 15:b = b - 1; m = m + 1; break;
            case 16:b = b - 1; n = n - 1; break;
            }
            if (a > 16) a = 1;
            if (b > 16) b = 1;
            if (m > 16) m = 1;
            if (n > 16) n = 1;
            if (a < 1) a = 16;
            if (b < 1) b = 16;
            if (m < 1) m = 16;
            if (n < 1) n = 16;
            if ((a == m) && (b == n))
            {
                t = false;
                if (t == false) cout << k << " ";
                break;
            }
        }
    }
}
c++

2个回答

错误为,srand的调用时间间隔太短(time(0)以秒作单位,则程序循环在1秒内rand()值完全一样,因此会重复计算,直至1秒之后结束该冗余计算过程)

解决方案:把代码行

srand((int)time(0));

移动到

for (int j = 0; j <= 10000; j++)

循环体之前即可

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问