Если мы выполняем приведение при использовании (int) (Math.random ()), не будет ли нашей переменной быть присвоено ноль, даже если мы умножим ее на другое значение? - PullRequest
0 голосов
/ 07 мая 2020

Я просматриваю несколько проектов мини-программирования в учебнике, и мне было интересно, если бы мы приводили к типу int в следующей программе, не было бы oneLength, twoLength, threeLength все присвоить значение 0? Я знаю, что, поскольку мы приводим к типу int, значения будут от 0 до 1, а это означает, что 0 будет включительно, а 1 - исключительным. Если у нас есть 0 * (12), 12 - длина wordListOne в качестве примера, не будет ли окончательное значение 0?

Вот программа:

publi c class 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); }}

Очень признателен за помощь, которую я получаю, и большое вам спасибо.

1 Ответ

1 голос
/ 07 мая 2020
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..

...