算术运算符:Java中共有9个算术运算符,包括5个二元运算符和4个一元运算符。
1、二元运算符:
二元运算符分别是+(加)、-(减)、*(乘)、/(除)和%(取余),其中+、-、*、/的操作数可以是任何数值型数据。
注意:①在进行除法运算时,整型数和整型数相除得到的也是整型数,如4/3=1;
②取余运算时,两个数必须是整数,并且结果的符号取决于第一个数。
③+、-的优先级低于另外三个。
设计算术运算符:一个简单的计算器,完成两个数的加、减、乘、除、取余
package test;
public class Main {
public static void main(String[] args) {
int tempFirstInt, tempSecondInt, tempResultInt;//先定义再赋值可以方便后面修改数值
double tempFirstDouble, tempSecondDouble, tempResultDouble;//命名尽量满足驼峰命名法,即第一个单词小写后面的单词首字母大写
tempFirstInt = 12;
tempSecondInt = 8;
//带有小数点的数值数是浮点数。浮点数所表示的数值是有误差。
tempFirstDouble = 2.4;
tempSecondDouble = 1.5;
//Addition(加法)
tempResultInt = tempFirstInt + tempSecondInt;
tempResultDouble = tempFirstDouble + tempSecondDouble;
System.out.println("" + tempFirstInt + " + " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " + " + tempSecondDouble + " = " + tempResultDouble);
//Subtraction(减法)
tempResultInt = tempFirstInt - tempSecondInt;
tempResultDouble = tempFirstDouble - tempSecondDouble;
System.out.println("" + tempFirstInt + " - " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " - " + tempSecondDouble + " = " + tempResultDouble);
//Multiplication(乘法)
tempResultInt = tempFirstInt * tempSecondInt;
tempResultDouble = tempFirstDouble * tempSecondDouble;
System.out.println("" + tempFirstInt + " * " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " * " + tempSecondDouble + " = " + tempResultDouble);
//Division(除法)
tempResultInt = tempFirstInt / tempSecondInt;
tempResultDouble = tempFirstDouble / tempSecondDouble;
System.out.println("" + tempFirstInt + " / " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " / " + tempSecondDouble + " = " + tempResultDouble);
//Modulus(取余)
tempResultInt = tempFirstInt % tempSecondInt;
System.out.println("" + tempFirstInt + " % " + tempSecondInt + " = " + tempResultInt);
}// Of main
}// Of class Main
2、一元运算符:
一元算术运算符是指一个操作数的运算,有以下几个:+(取正)、-(取负)、++(变化值增加)和--(变量值减一)。
注意:++变量:表示先加后用;变量++:表示先用后加;要特别注意这里。
Question:浮点数所表示的数值是有误差,不能绝对相等,那如何判断两个浮点数相等呢?
Answer:Math.abs(firstDouble-secondDouble)<1e-6
如果两个double的差距不超过10的-6次方,就认为是相等的。