如何根据事件发生的概率在 php 中执行一个事件

发布于 2025-01-05 04:54:48 字数 246 浏览 2 评论 0原文

我想要这样的东西:

$chance = 40; //40%
if ( run the probability check script ) {
    echo "event happened"; //do the event
}
else {
   echo "event didn't happened";
}

实现这样的事情的最佳解决方案是什么?

多谢!

i want something like this:

$chance = 40; //40%
if ( run the probability check script ) {
    echo "event happened"; //do the event
}
else {
   echo "event didn't happened";
}

what is the best solution to achieve something like that?

thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苍风燃霜 2025-01-12 04:54:48

使用rand()

if (rand(1,100)<=$chance)

这将返回1到100之间的数字,因此它的概率是小于或等于 40 为 40%。

Use rand():

if (rand(1,100)<=$chance)

This will return a number between 1 and 100, so that the probability of it being lower or equal to 40 is 40%.

囍孤女 2025-01-12 04:54:48

嗯...要么我失去了它,要么你的意思是你想要下面的...

$chance = 40;
if ($chance >= 40){
    echo "event happened"; //do the event
} else {
   echo "event didn't happened";
}

这假设机会等于或大于 40。

如果你希望机会随机生成,那么使用类似 $chance = rand(0,100); 对于 0 到 100 之间的随机数 - 然后只需使用 if 语句来执行条件。

归根结底,这取决于您的初始 $chance 是固定数字还是随机数字或作为计算结果发生......不幸的是您没有提供太多见解...... 。

Umm... Either I'm losing it or you mean you want the below...

$chance = 40;
if ($chance >= 40){
    echo "event happened"; //do the event
} else {
   echo "event didn't happened";
}

This assumes that the chance is equal to or is more than 40.

If you want chance to be randomly generated, then use something like $chance = rand(0,100); for a random number between 0 and 100 - then just use if statements to do the conditions.

At the end of the day it depends if your initial $chance is a fixed number or it is random or occurs as a result of a calculation.... unfortunately you haven't provided much insight...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文