【问题标题】:What is wrong with this code for generating random integers in Java??? (Unexpected Outputs) [closed]这个用Java生成随机整数的代码有什么问题??? (意外输出)[关闭]
【发布时间】:2021-02-10 08:44:53
【问题描述】:

下面的代码应该生成从 97 到 122 的随机整数:

for(int x = 0; x < 10; x++) {
    int a = (int)(Math.random()*(26 + 97));
    System.out.println(a);
} 

我得到的输出到处都是。他们低于97。 以下是其中一次运行的输出:

33
113
87
73
22
25
118
29
16
21

【问题讨论】:

  • 是的,这更像是一道基本的数学题^^

标签: java eclipse random integer


【解决方案1】:

这是一个问题。试试这个吧。

(int)(Math.random()*26) 给出一个介于 0 和 25 之间的数字。
将 97 添加到该范围,您将得到 97 到 122(含)。

int a = (int)(Math.random()*26) + 97;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多