Calculator addition and subtraction
Topic:
Correctly use method overloading to realize a simple calculator, realize the addition of two integers and three floating-point numbers respectively, and output the result of the addition on the console. The output of the calculator is shown in the figure.
Problem-solving ideas:
1. 先读认真读题,题目要求使用方法重载,完成两个整数,三个浮点数的加法
2. 如果直接赋值,这样的话,就直接把数写死了,不能够灵活运用
3. 所以,我们可以在控制台让用户输入这两个整数和三个浮点数,要用到Scanner
4. 将用户输入的数放在数组中保存
5. 再进行重载,一个是完成整数的加法,一个完成小数的加法
The effect is achieved:
The output here can be changed to be more vivid, it's up to you to complete it!
Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Add a = new Add();
int[] arrs = new int[2];
for (int i = 0; i < arrs.length; i++) {
System.out.print("请输入第"+(i+1)+"个整数:");
arrs[i]= sc.nextInt();
}
float[] arrs1=new float[3];
for (int i = 0; i < arrs1.length; i++) {
System.out.print("请输入第"+(i+1)+"个小数:");
arrs1[i]=sc.nextFloat();
}
a.add(arrs[0],arrs[1]);
a.add(arrs1[0],arrs1[1],arrs1[2]);
}
public void add(int a,int b){
System.out.println(a+b);
}
public void add(float a,float b,float c){
System.out.println(a+b+c);
}
Note: When adding and subtracting decimals, there may be accuracy problems in the output, so don't worry about it!