标题: 运算符的运算 [打印本页] 作者: 814326663 时间: 2015-4-16 20:42 标题: 运算符的运算 /**--------文件名:Operator.java-------------*/
// author : 814326663 孤狼
class Operator {
/**
* 计算运算符: +; -; *; /;
*/
private void computeOperator() {
int a = 8;
int b = 5;
// 对于除法运算,根据基本类型的自动转换规则,当除数和被除数都是整数时,
// 得到的结果也是整数。因此 8/5得到的是1,而不是1.6
int f = a / b;
double g = a / b;
System.out.println("(f = a / b) = " + f + "; (g = a / b) = " + g);
// 只要除数和被除数中有一个为double或者float,结果就不同了,8/5.0得到是1.6
double h = a / (b * 1.0d);
float i = a / (b * 1.0f);
System.out.println("(h = a / (b * 1.0d)) = " + h + "; (i = a / (b * 1.0f)) = " + i);
}
/**
* 比较运算符: ==; <; >; !=; <=; >=;
*/
private void compareOperator() {
int a = 5;
int b = 10;
System.out.println("(a == b) = " + (a == b));
System.out.println("(a < b) = " + (a < b));
System.out.println("(a > b) = " + (a > b));
System.out.println("(a != b) = " + (a != b));
System.out.println("(a <= b) = " + (a <= b));
System.out.println("(a >= b) = " + (a >= b));
System.out.println("(a = b) = " + (a = b)); // 10
}
// 可以用三目运算符替代简单的if语句
// 格式是: x = a ? b : c;如果a的值为true,则将b的值赋予x,否则将c的值赋予x。
int x = (i >= 0) ? i : -i; // 将一个减号-和数字连用,是取数字的负数
System.out.println("i的绝对值为: " + x);
}
public static void main(String[] args) {
Operator test = new Operator();
System.out.println("计算运算符方法的输出:");
test.computeOperator();
System.out.println("比较运算符方法的输出:");
test.compareOperator();
System.out.println("位运算符方法的输出:");
test.bitOperator();
System.out.println("布尔运算符方法的输出:");
test.booleanOperator();
System.out.println("赋值运算符方法的输出:");
test.evaluateOperator();
System.out.println("其他运算符方法的输出:");
test.otherOperator();
}
}