如何使用Dart生成随机数?


当前回答

对我来说,最简单的方法是:

import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.

感谢@adam-singer的解释。

其他回答

无法评论,因为我刚刚创建了这个帐户,但我想确保指出,@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

一行解决方案,您可以直接调用所有函数的构造函数以及。

import 'dart:math';

print(Random().nextInt(100));

您可以简单地用这种方式生成 有一个名为Random()的类;

你可以用它来生成随机数

Random objectname = Random();
int number = objectname.nextInt(100);
// it will generate random number within 100.

对我来说,最简单的方法是:

import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.

感谢@adam-singer的解释。

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

它会给出0到99的随机数

Eample::

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