• Dart如何生成最小值和最大值之间的随机数
  • 发布于 2个月前
  • 597 热度
    0 评论
在 Dart(以及 Flutter)中生成给定范围内的随机整数的几个示例。
示例 1:使用 Random().nextInt() 方法
import 'dart:math';
randomGen(min, max) {
  //nextInt 方法生成一个从 0(包括)到 max(不包括)的非负随机整数
  var x = Random().nextInt(max) + min;
  //如果您不想返回整数,只需删除 floor() 方法
  return x.floor();
}
void main() {
  int a = randomGen(1, 10);
  print(a);


}
输出:
8 // you may get 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

您得到的结果可能包含最小值、最大值或此范围内的值。


示例 2:使用 Random.nextDouble() 和 floor() 方法
代码:
import 'dart:math';

randomGen(min, max) {
  // nextDouble() 方法返回一个介于 0(包括)和 1(不包括)之间的随机数
  var x = Random().nextDouble() * (max - min) + min;

  // 如果您不想返回整数,只需删除 floor() 方法
  return x.floor();
}

// Testing
void main() {
  // with posstive min and max
  print(randomGen(10, 100));
  
  // with negative min 
  print(randomGen(-100, 0));
}
输出(输出当然是随机的,每次重新执行代码时都会改变)。
47
-69
您得到的结果可能会包含 min 但绝不会包含 max。
用户评论