Java基础题_2021/12/3

# 剑指offer

1.四舍五入

image-20211203153531153

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double d= scanner.nextDouble();
		//强制类型转换会去掉小数
        int i=(int)d;
        //判断强转之后的i和d的差值,如果大于0.5那就需要“入”
        if((d-i)>0.5){
            i++;
        }
        System.out.println(i);
    }
}

2.交换变量值

image-20211203154457785

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        //使用括号优先级改变运算优先级顺序,但是程序读取顺序没变
        a=a+b-(b=a);

        System.out.println(a+" "+b);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        a=a+b;
        b=a-b;
        a=a-b;

        System.out.println(a+" "+b);
    }
}

3.商场计算折扣

image-20211203160532375

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        int price = console.nextInt();
        int cost = 0;

        //write your code here......
        //write your code here......
        if(price>=5000){
            cost=(int)(price*0.6);
        }
        else if(price>=2000){
            cost=(int)(price*0.7);
        }
        else if(price>=500){
            cost=(int)(price*0.8);
        }
        else if(price>=100){
            cost=(int)(price*0.9);
        }else if(price>0&&price<100){
            cost=(int)price;
        }

        System.out.println(cost);
    }
}

​ 这个题并不难,需要注意的是:1.不能直接用if一直循环,因为限制条件只有一端,例如:如果price>500,它会把后几个循环一起执行了然后输出最后的cost值;2.使用else if,但是注意else if是分开写的。

posted @ 2021-12-04 14:36  Mr_WildFire  阅读(45)  评论(0编辑  收藏  举报