jave中的Random中rand.nextInt(int n )的取值範圍

1.要求在10到300中產生隨機數[10,300]包含10和300.

int randNum = rand.nextInt(300-10+1) + 10;

rand.nextInt(300-10+1)=rand.nextInt(291)意思是產生[0,291)不包括291再加10就是[10,301)不包括301,如果要包括300所以要 rand.nextInt(300-10+1)裏面要加1.


如果是[10,300)不包括300就是 rand.nextInt(300-10)+10,不要加1.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章