1、double y = 2.825423; 四舍五入取三位小数/
public class Demo4 {
public static void main(String[] args) {
double y = 2.825423;
//方式一:使用BigDecimal实现四舍五入(支持float和double类型)
double result = new BigDecimal(y).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("四舍五入后的结果为"+result);
//方法二:
System.out.println((int)(y*1000+0.5)/1000.0);
}
}
2、随意定义一个变量i = 3287;获取该数字中各个位上的数字
最终输出:个位是7, 十位是8,百位是2, 千位是3/
public class Demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 3287;
System.out.println("个位是"+i%10);
System.out.println("十位是"+i/10%10);
System.out.println("百位是"+i/100%10);
System.out.println("千位是"+i/1000%10);
}
}
3、给定i和j,int i = 10, j = 20; int z = (i++) + (++j) + (++i)*2 + (j++)*3
不要写代码,计算i、j、z的值
**执行i++时,i的值为10
执行++j时,i的值为11,j的值21
执行(++i)2时,i的值为12,j的值为21
执行(j++)3时,i的值为12,j的值为21
4.定义一个int变量,使用三元运算符,输出这个变量是否可以被7整除
例如,定义变量int a = 10;
最终输出:变量值为10,该变量不能被7整除
public class Demo3 {
public static void main(String[] args) {
int a = 10;
String m = a%7==0?"该整数能被7整除":"该整数不能被7整除";
System.out.println(m);
}
}
5.int x = 12345, 求各个位上数字之和
public class Demo7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 12345;
System.out.println(x/10000+x/1000%10+x/100%10+x/10%10+x%10);
}
}
6.使两个数的数值进行交换
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//方法一,采用中间值temp法
int a=1;
int b=2;
System.out.println("交换前,a的值为"+a+" b的值为"+b);
int temp = a;
a = b;
b = temp;
System.out.println("交换后,a的值为"+a+" b的值为"+b);
System.out.println("##############################");
//方法二,不采用temp解决办法
int m = 3;
int n = 4;
System.out.println("交换前,m的值为"+m+" n的值为"+n);
m=m+n;
n=m-n;
m=n;
System.out.println("交换后,m的值为"+m+" m的值为"+n);
}
}
7.最快计算3乘2的四次方
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print(3<<4);
}
}