Compare
All relational operators have lower precedence than arithmetic operations, but higher precedence than assignment operations;
equality == and != have lower precedence than others, and successive relational operations are performed from left to right ;
package hello;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
double a = 1.0;
double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
System.out.println(a);
System.out.println(b);
System.out.println(a == b);
System.out.println(Math.abs(a - b) < 1e6);
//浮点数的运算有误差 所以用两个数的绝对值小于某一个精度
}
}
if-else
package hello;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("请输入你的年龄:");
int a = in.nextInt();
System.out.println("你的年龄:" + a);
if(a < 20)
{
System.out.println("你的年龄是美好的!");
}
else
{
System.out.println("该好好努力了!");
}
System.out.println("好好珍惜吧!");
}
}
branch
package hello;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int a = in.nextInt();
double f;
if(a > 0)
{
f = 0.1;
}else if(a < 0)
{
f = -0.1;
}else
{
f = 0;
}
System.out.println(f);
}
}
switch-case
package hello;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int type = in.nextInt();
double f;
switch(type) {
case 1:
f = 0.1;
break;
case 2:
f = 0.2;
break;
default:
f = 0;
break;
}
System.out.println(f);
}
}