Rand.nextint(a)* B + C(java随机生成器问题) [英] Rand.nextint(a) * B + C (java random generator problem)

查看:277
本文介绍了Rand.nextint(a)* B + C(java随机生成器问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Write code that generates a random odd integer (not divisible by 2) between 50 and 99 inclusive. Fill in the values of the sub-expressions labeled A, B, and C below.

Random rand = new Random(); int n = rand.nextInt(A) * B + C;







答案是A = 25; B = 2; C = 51



我尝试过:






The answer is A = 25; B = 2; C =51

What I have tried:

I dont get the answer. rand.nextInt(25) meansa range of  0-24 right.  Then, you multiply by 2 so the range becomes 0-48. Last you add 51 so the final range becomes  51 - 99, but the problem says the range is 50-99. Can someone explain to me how to get range of 50-99 with answers of A = 25; B = 2; C =51

推荐答案

您需要仅生成奇数:所以您添加的值 - C - 必须是奇数,原始值 - rand.nextInt(A)* B 必须是偶数,这意味着 B 必须是偶数。

所以你的导师选择了B = 2,C = 51,它满足了必须奇怪的要求,并抵消了这个数字,以便它在任何情况下都是51或更高。由于51是大于50的第一个奇数值,它也适合该范围的低端。

A控制原始值范围:25确实会给出0到24之间的数字,所以完整表达式将给出如下值:

You are required to generate odd numbers only: so the value you add on - C - must be odd, and the original value - rand.nextInt(A) * B must be even, which means that B must be even.
So your tutor has selected B = 2, C = 51 which fulfils the "must be odd" requirement, and offsets the number so that it is 51 or greater under all circumstances. Since 51 is the first odd value greater than 50 it fits the low end of the range as well.
A controls the original range of values: 25 will indeed give you numbers from 0 to 24, so the complete expression will give values like this:
A = 0 :  0 * 2 + 51 ==  0 + 51 == 51
A = 1 :  1 * 2 + 51 ==  2 + 51 == 53
A = 2 :  2 * 2 + 51 ==  4 + 51 == 55
...
A = 22: 22 * 2 + 51 == 44 + 51 == 95
A = 23: 23 * 2 + 51 == 46 + 51 == 97
A = 24: 24 * 2 + 51 == 48 + 51 == 99

符合您的所有条件。


Quote:

51 - 99,但问题是范围是50-99。

51 - 99, but the problem says the range is 50-99.

确实是taht的范围。但是,不幸的是 50 是偶数,因此 51 是请求范围的第一个有效条目。

Indeed taht's the range. But, unfortunately 50 is even, hence 51 is the first valid entry of the requested range.


这篇关于Rand.nextint(a)* B + C(java随机生成器问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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