如果我们在使用 (int)(Math.random()) 时进行强制转换,即使我们乘以另一个值,我们的变量也不会被赋值为零吗?



我正在教科书中运行一些迷你编程项目,我想知道,如果我们在下面的程序中转换为 int 类型,oneLengthtwoLengththreeLength不是都被分配了一个值 0 吗?我知道由于我们要转换为 int,因此值将从 0 到 1,这意味着 0 将是包含的,而 1 是排除的。如果我们以 0 * (12) 为例,12 是wordListOne的长度,最终值不是 0 吗?

这是程序:

公共类 ScribblePad {

public static void main(String[] args) {
String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win", "front-end", "web-based", "pervasive", "smart", "six-sigma", "critical-patch", "dynamic"};
String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};
String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "mission"};

// oneLength : number of items in array
int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// rand1 : casting to int value
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);

// phrase : 
String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
System.out.println("What we need is a " + phrase); }}

非常感谢我得到的帮助,非常感谢你。

int rand1 = (int) (Math.random() * oneLength);

我们知道oneLength == 12.

图像,如果Math.random()给你0.72- 现在将其乘以12- 结果是9.12- 现在将其转换为整数 - 结果是9.

你会得到一个值0,以防Math.random()给你一个小于0,0833..的数字,为什么?

因为:12 * x < 1 => x < 1/12 = 0.0833..

相关内容

最新更新