如何从Java中的randDouble获得1到100之间的随机值? [英] How to get a random between 1 - 100 from randDouble in Java?

查看:389
本文介绍了如何从Java中的randDouble获得1到100之间的随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我还是Java的新手。我们已经获得了一个帮助来创建一个游戏,您必须猜测计算机生成的随机整数。问题是我们的讲师坚持要求我们使用:

Okay, I'm still fairly new to Java. We've been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem is that our lecturer is insisting that we use:

double randNumber = Math.random();

然后将其转换为接受1 - 100(包括1和100)的随机整数。我有点不知所措。到目前为止我所拥有的是:

And then translate that into an random integer that accepts 1 - 100 inclusive. I'm a bit at a loss. What I have so far is this:

//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;

//Type cast double to int
int randomInt = (int)d;

然而,随机双重延迟问题的随机性是0是可能的,而100不是。我想改变它,以便0不是可能的答案,100是。救命?

However, the random the lingering problem of the random double is that 0 is a possibility while 100 is not. I want to alter that so that 0 is not a possible answer and 100 is. Help?

推荐答案

你快到了。只需在结果中加1:

You're almost there. Just add 1 to the result:

int randomInt = (int)d + 1;

这会将你的范围转移到 1 - 100 而不是 0 - 99

This will "shift" your range to 1 - 100 instead of 0 - 99.

这篇关于如何从Java中的randDouble获得1到100之间的随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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