java运算符
数学整个程序的基础,所以各种常用的计算符号,基本java都会提供。程序可以提供的只是最为基础的数学运算支持,如果需要完成更为复杂的计算,你需要自己进行二进制的处理了。
在以后你写的代码之中,千万别写出以下的复杂计算:
public class Math{
public static void main(String args[]) {
int x = 10;
int y = 20;
int result = x - y++ + x * y -- - --x * y / x--;
System.out.println(result);//180
}
}
对于程序的计算而言,千万别写的谁也不知道。以后写的代码都写简单代码。
基本四则运算实例:
public class Math1{
public static void main(String args[]) {
int x = 10;
int y = 20;
System.out.println(x - y);//-10
System.out.println(x + y);//30
System.out.println(x * y);//200
System.out.println(x / y);//0
}
}
但是也需要考虑另外一种情况,所有的运算符都是有其优先级的,这些优先级不需要背,一般用括号来改变优先级。
public class Math2{
public static void main(String args[]) {
int x = 10;
int y = 20;
System.out.println((x - y)*(x + y));//-300
}
}
另外在数学计算里面有一个自增和自减的操作。
自增运算:
- ++ 变量:先自增后进行运算
- 变量 ++:先运算再进行自增
自增观察:
public class Math3{
public static void main(String args[]) {
int x = 10;
int y = 20;
int result = ++x * y;
//++x先执行成11,然后11 * 20
System.out.println(result);//220
System.out.println(x);//11
int result1 = x++ * y;
//x*y,然后x自增
System.out.println(result1);//220
System.out.println(x);//12
}
}
如果实在记不住,就分开写。
自减运算:
- --变量:先进行自减处理,然后进行运算
- 变量--:先进行运算,而后进行自减处理