Java自学-操作符 算数操作符

Java的算数操作符

算数操作符
基本的有:

+ - * / %

自增 自减

++ --

基本的加 减 乘 除

public class HelloWorld {
    public static void main(String[] args) {
        int i = 10;
        int j = 5;
        int a = i+j;
        int b = i - j;
        int c = i*j;
        int d = i /j;
    }
}

示例 1 : 任意运算单元的长度超过int

如果有任何运算单元的长度超过int,那么运算结果就按照最长的长度计算
比如 :

int a = 5;
long b = 6;
a+b -> 结果类型是long

public class HelloWorld {
    public static void main(String[] args) {
 
        int a = 5;
        long b = 6;
        int c = (int) (a+b); //a+b的运算结果是long型,所以要进行强制转换
        long d = a+b;
         
    }
}

示例 2 : 任意运算单元的长度小于int

如果任何运算单元的长度都不超过int,那么运算结果就按照int来计算
byte a = 1;
byte b= 2;
a+b -> int 类型

public class HelloWorld {
    public static void main(String[] args) {
        byte a = 1;
        byte b= 2;
        byte c = (byte) (a+b); //虽然a b都是byte类型,但是运算结果是int类型,需要进行强制转换
        int d = a+b;
    }
}

示例 3: %取模

% 取余数,又叫取模
5除以2,余1

public class HelloWorld {
    public static void main(String[] args) {
 
        int i = 5;
        int j = 2;
        System.out.println(i%j); //输出为1
    }
}

示例 4 : 自增 自减

++ 
--

在原来的基础上增加1或者减少1

public class HelloWorld {
    public static void main(String[] args) {
 
        int i = 5;
        i++;
        System.out.println(i);//输出为6
 
    }
}

示例 5 :自增 自减操作符置前以及置后的区别

以++为例 :
int i = 5;
i++; 先取值,再运算
++i; 先运算,再取值

public class HelloWorld {
    public static void main(String[] args) {
        int i = 5;
        System.out.println(i++); //输出5
        System.out.println(i);   //输出6
         
        int j = 5;
        System.out.println(++j); //输出6
        System.out.println(j);   //输出6
    }
}

练习BMI

(使用 Scanner 收集你的身高体重,并计算出你的BMI值是多少

BMI的计算公式是 体重(kg) / (身高*身高)

比如xxx的体重是72kg, 身高是1.69,那么这位同学的BMI就是
72 / (1.69*1.69) = ?)

猜你喜欢

转载自www.cnblogs.com/jeddzd/p/11376630.html