如何使用Dart生成随机数?


当前回答

无法评论,因为我刚刚创建了这个帐户,但我想确保指出,@eggrobot78的解决方案是有效的,但它在dart中是独占的,所以它不包括最后一个数字。如果您将最后一行更改为“r = min + rnd.”nextInt(max - min + 1);”,那么它也应该包括最后一个数字。

解释:

max = 5;
min = 3;
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//max - min is 2
//nextInt is exclusive so nextInt will return 0 through 1
//3 is added so the line will give a number between 3 and 4
//if you add the "+ 1" then it will return a number between 3 and 5

其他回答

它为我工作new Random().nextInt(100);// MAX = number

它会给出0到99的随机数

Eample::

import 'dart:math';
int MAX = 100;
print(new Random().nextInt(MAX));`

试试这个,你可以控制最小/最大值:

注意,您需要导入省道数学库。

import 'dart:math';

void main() {
  
  int random(int min, int max) {
    return min + Random().nextInt(max - min);
  }

  print(random(5, 20)); // Output : 19, 5, 15.. (5 -> 19, 20 is not included)
}

你可以通过在dart:math库中的随机类对象Random . nextint (max)来实现它。nextInt()方法需要一个最大限制。随机数从0开始,最大限制本身是排他的。

import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included

如果要添加最小限制,请将最小限制添加到结果中

int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included

使用'dart:math'库中的类Random()。

import 'dart:math';

void main() {
  int max = 10;
  int RandomNumber = Random().nextInt(max);
  print(RandomNumber);
}

这将生成并打印一个从0到9的随机数。

刚刚写了这个小类来生成正态随机数…对于我需要做的检查来说,这是一个很好的起点。(这些套将分布在一个“钟”形 曲线)。种子是随机设置的,但如果你想重新生成一个集合你只需要传递一些特定的种子,同样的集合就会生成。

玩得开心…

class RandomNormal {
  num     _min, _max,  _sum;
  int     _nEle, _seed, _hLim;
  Random  _random;
  List    _rNAr;

  //getter
  List get randomNumberAr => _rNAr;

  num _randomN() {
    int r0 = _random.nextInt(_hLim);
    int r1 = _random.nextInt(_hLim);
    int r2 = _random.nextInt(_hLim);
    int r3 = _random.nextInt(_hLim);

    num rslt = _min + (r0 + r1 + r2 + r3) / 4000.0;  //Add the OS back in...
    _sum += rslt; //#DEBUG ONLY
    return( rslt );
  }

  RandomNormal(this._nEle, this._min, this._max, [this._seed = null]) {
    if (_seed == null ) {
      Random r = new Random();
      _seed    = r.nextInt(1000);
    }
    _hLim   = (_max - _min).ceil() * 1000;
    _random = new Random(_seed);
    _rNAr   = [];
    _sum    = 0;//#DEBUG ONLY

    h2("RandomNormal with k: ${_nEle}, Seed: ${_seed}, Min: ${_min}, Max: ${_max}");//#DEBUG ONLY
    for(int n = 0; n < _nEle; n++ ){
      num randomN = _randomN();
      //p("randomN  = ${randomN}");
      LIST_add( _rNAr, randomN );
    }

    h3("Mean = ${_sum/_nEle}");//#DEBUG ONLY
  }
}


new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);

然后您可以像这样使用它来检查在低和高限制之间生成的1000个nums集的平均值。值存储在类中,以便在实例化后可以访问它们。

_swarmii