public class MainClass{
public static void main(String[] args) throws Exception {
System.out.println(Math.round(15.5)); // 16
System.out.println(Math.round(-15.5)); // -15
System.out.println(Math.round(-15.51)); // -16
}
}
如果进行负数四舍五入的时候,操作的数据小数位大于0.5才进位,小于等于0.5不进位。
Random类
这个类的主要功能是取得随机数的操作类。
范例: 产生10个不大于100的正整数(0~99)
public class MainClass{
public static void main(String[] args) throws Exception {
Random random = new Random();
for (int i = 0; i < 10; i ++) {
System.out.print(random.nextInt(100) + "、");
}
}
}
既然Random可以产生对技术,下面就希望利用其来实现一个36选7的功能。
范例: 36选7
public class MainClass{
public static void main(String[] args) throws Exception {
Random random = new Random();
int[] date = new int[7]; // 开辟一个7个元素的数组
int foot = 0; // 此为数组操作交表
while (foot < 7) { // 不知道多少次循环可以保存完数据,所以使用while循环
int t = random.nextInt(37); // 生成一个不大于37的随机数
if (!isRepeat(date, t)) { // 重复
date[foot ++] = t; // 保存数据
}
}
Arrays.sort(date);
for (int i = 0; i < date.length; i ++) {
System.out.print(date[i] + ", ");
}
}
/**
* 此方法主要是判断是否存在有重复的内容,但是不允许保存0
* @param temp 指的是已经保存的数据
* @param num 新生成的数据
* @return 如果成功的保存了,那么返回true,否者返回false
*/
public static boolean isRepeat(int[] temp, int num) {
if (num == 0) { // 没有必要向下继续判断
return true;
}
for (int i = 0; i < temp.length; i ++) {
if (temp[i] == num) {
return true;
}
}
return false;
}
}