gpt4 book ai didi

php - 如何按百分比运行代码

转载 作者:行者123 更新时间:2023-12-02 07:40:14 24 4
gpt4 key购买 nike

在我的脚本中,我想在一定百分比的时间内运行特定代码,我查看了 StackOverflow 并找到了下面的代码。它在 33% 的时间内运行代码,我需要修改什么才能让它在 55% 和 70% 的时间内运行?

$max = 27;

for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}

最佳答案

最简单的方法是使用随机数生成器并测试其结果是否小于(或大于,无关紧要)您的目标数量。

function percentChance($chance){
// Notice we go from 0-99 - therefore a 100% $chance is always larger
$randPercent = mt_rand(0,99);
return $chance > $randPercent;
}

...

if(percentChance(30)){
// 30% of page loads will enter this block
}

if(percentChance(100)){
// All page loads will enter this block
}

if(percentChance(0)){
// No chance this block will ever be entered
}

关于php - 如何按百分比运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com