int random = (int) (Math.random() * 10 + 1);//此代码随机生成[1,10]之间的数
Math.random是double浮点数类型,因为是用int类型接收,所以应把(Math.random() * 10 + 1)强转为int类型
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import java.util.Scanner; public class Random { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请你猜一猜:"); Scanner sc = new Scanner(System.in); int random = (int) (Math.random() * 10 + 1); int i; for (i = 1;; i++) { int sum = sc.nextInt(); if (sum == random) { System.out.println("猜对了,是" + random); break; } } System.out.println("猜了" + i + "次"); } }
最后
以上就是魔幻短靴最近收集整理的关于Math.random随机数的使用的全部内容,更多相关Math.random随机数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复