对于我正在编写的游戏,我需要 求两组坐标之间距离的整数值. 。它是 二维阵列 持有不同的地图。(就像原来的塞尔达)。你离的越远 中心 (5,5) 由于敌人的难度增加,数字应该越高。理想情况下应该是 0 到 14 之间. 。这 数组为 11x11.

现在,我尝试使用 毕达哥拉斯 我高中时记得的公式,但它正在喷涌而出 溢出数字. 。我不明白为什么。

        srand(rand());
        int distance=sqrt(pow((5-worldx), 2)-pow((5-worldy), 2));
        if(distance<0) //alternative to abs()
        {
            distance+=(distance * 2);
        }
        if(distance>13)
        {
            distance=13;
        }

        int rnd=rand()%(distance+1);

        Monster testmonster = monsters[rnd];
有帮助吗?

解决方案

srand(rand()); 没有意义,应该是 srand(time(NULL));

不要使用 pow 对于正方形,只需使用 x*x

你的公式也错了,你应该把数字加在一起而不是减

sqrt 返回 double 并投射到 int 将其四舍五入

我认为 sqrt 总是返回正数

你知道 abs 存在吗?为什么不使用它呢?还 distance = -distancedistance+=(distance * 2)

srand(time(NULL));

int dx = 5 - worldx;
int dy = 5 - worldy;
int distance=sqrt(dx * dx + dy * dy);
if(distance>13)
{
    distance=13;
}

int rnd=rand()%(distance+1);

Monster testmonster = monsters[rnd];

其他提示

它是一个^ 2 + b ^ 2= c ^ 2,而不是减去。一旦你用否定参数调用sqrt,你就是自己的。

你在平方根里面减去了正方形,而不是添加它们(“... - pow ...”)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top