sdut-oop-8 小小算术四则运算器(类和对象)

根据输入的2个整数(x和y),计算它们的绝对值之和、差、积、商并输出。

若除数y为0,则不能进行除法运算,输出一个标志值,表示形式为:Integer.MAX_VALUE(int类型的最大值)。

提示:在Java中,利用Math类的静态方法 Math.abs(x) 来计算x的绝对值。

函数接口定义:

class Calculator {
    int x;
    int y;
 
    public Calculator(int x, int y) {
    
        
    } 
    public int add()  //求和
    {
        return 0;
    }
    public int sub()  //求差
    {
        return 0;
    }
    public int mul()  //求积
    {
        return 0;
    }
    public int div()  //求商
    {
        if(      )
            return 0;
        else
            return Integer.MAX_VALUE;
    }
}

裁判测试程序样例: 

在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x=input.nextInt();
        int y=input.nextInt();
        Calculator cal=new Calculator(x, y);
        int sum=cal.add();
        int sub=cal.sub();
        int mul=cal.mul();
        int div=cal.div();
        System.out.println(sum+" "+sub+" "+mul+" "+div);
    }
}  

/* 请在这里填写答案 */

输入样例1:

在这里给出一组输入。例如:

1 2

输出样例1:

在这里给出相应的输出。例如:

3 -1 2 0

输入样例2:

在这里给出一组输入。例如:

1 -2

输出样例2:

在这里给出相应的输出。例如:

3 -1 2 0

输入样例3:

在这里给出一组输入。例如:

100 0

输出样例3:

在这里给出相应的输出。例如:

100 100 0 2147483647

 


答案:

class Calculator {
    int x;
    int y;
 
    public Calculator(int x, int y) {
    	this.x=x;
    	this.y=y;
        
    } 
    //计算它们的"绝对值"之和、差、积、商并输出。
    //在Java中,利用Math类的静态方法 Math.abs(x) 来计算x的绝对值。
    public int add()  //求和
    {
        return  Math.abs(x)+Math.abs(y);
    }
    public int sub()  //求差
    {
        return Math.abs(x)-Math.abs(y);
    }
    public int mul()  //求积
    {
        return Math.abs(x)*Math.abs(y);
    }
    public int div()  //求商
    {
        if( y!=0 )
            return Math.abs(x)/Math.abs(y);        //刚开始漏掉了,返回的0,所以部分正确
        else
            return Integer.MAX_VALUE;
    }
}

tips:

                add 求和        sub 求差

                mul 求积        div 求商

                Math.abs() 求绝对值

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值