根据输入的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() 求绝对值