javascript - 如何使用javascript根据变量的值设置随机百分比机会
问题描述
假设我有一个值为 5 的变量,变量的值越高,成功的机会就越高。
那么我怎么能做这样的事情呢?:
function mission1() {
if (user_power < 5) {
//30% change of succes
} else if (user_power == 5) {
//50% change of succes
} else if (user_power > 5) {
//80% change of succes
}
解决方案
我不知道我是否正确理解了您想要什么,但这是我的解决方案:
function mission1(user_power) {
if (user_power < 5) {
// 30% chance of succes
return Math.random() < 0.3;
} else if (user_power == 5) {
//50% chance of succes
return Math.random() < 0.5;
} else if (user_power > 5) {
//80% chance of succes
return Math.random() < 0.8;
}
}
该函数根据给定的参数返回一个布尔值。
注意: Math.random() 返回一个介于 0 和 1 之间的浮点数,因此它低于 0.8 的可能性是 80%。
推荐阅读
- td-engine - 无法更改 TDengine 数据库中的更新选项?
- oracle - oracle ords docker镜像的连接字符串无效
- swift - 在 SwiftUI 中,如何在 LinkedList 中“Foreach”节点?
- active-directory - adprep /rodcprep WS2008 和 WS2019
- elasticsearch - 为什么 Elasticsearch 中的 scaled_float 类型名称中有“float”?
- firebase - 将我的应用程序升级为空安全后,文档下的红线
- jestjs - 在 stencilJS 中使用 ref jest 单元测试用例在 componentDidLoad 上输入自动对焦错误
- batch-file - 为什么 MSG 命令在 IF 语句中不起作用?
- rcpp - 立方体中每个切片的操作
- c - 如何在不使用数组、指针或结构的情况下返回多个值?