Java随机数 [英] Java random number

查看:54
本文介绍了Java随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是初学者的问题:我尝试使用此代码创建随机数

Beginner question here: I tried creating a random number using this code

int rand = (int) Math.random()*10;

但是,在屏幕上打印时,我一直收到0作为答案

however, i kept receiving 0 as the answer when printing to screen

仅在像这样加上括号之后

only after putting parenthesis like so

int rand = (int)(Math.random()*10);

该数字显示正确了吗?谁能解释我错过的逻辑原因?

did the number show properly. Can anyone explain the logical reason for this that I missed?

推荐答案

代码

int rand = (int) Math.random()*10;

等同于

int rand = ((int) Math.random()) * 10; 

因此, Math.random()的值将转换为 int .因为该值介于0和1之间(排除1),所以它会转换始终为零.

So the value of Math.random() is converted to an int. Because that value is between 0 and 1 (1 excluded) it is converted always to zero.

所以

(int) Math.random()*10 -->  ((int) Math.random()) * 10 --> 0 * 10 --> 0

这篇关于Java随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆