给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。
说明:
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generate-random-point-in-a-circle 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
在 [-1,1] 上的随机位置,如果在单位圆内就输出(概率78.5%),否则继续找
class Solution {
double r;
double x, y;
double cos_theta, sin_theta;
public:
Solution(double radius, double x_center, double y_center) {
r = radius;
x = x_center;
y = y_center;
}
vector<double> randPoint() {
do
{
cos_theta = 2*(double)rand()/RAND_MAX - 1;
sin_theta = 2*(double)rand()/RAND_MAX - 1;
}
while(sin_theta*sin_theta + cos_theta*cos_theta > 1);//在圆外
return {x+r*cos_theta, y+r*sin_theta};
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有