有一个函数
y=x (x<1)
y=2x-1 (1<=x<10)
y=3x-11 (x>=10)
写一个方法getValue(),对任意参数x,返回y的值
首先按照题目要求 写一个方法getValue(),接收一个整数类型的参数,并向主方法返回一个整数型参数
public static void main(String args[]){ } public static int getValue(int x){ }
接下来在子方法中判断当x的三种条件时,y的值。
public static void main(String args[]){ } public static int getValue(int x){ int y=0; if(x<1){ y=x; }else if(x>=1 && x<10){ y=2*x-1; }else{ y=3*x-11; } }
返回y,并在主方法中定义变量y接收
public static void main(String args[]){ int y=getValue(); } public static int getValue(int x){ int y=0; if(x<1){ y=x; }else if(x>=1 && x<10){ y=2*x-1; }else{ y=3*x-11; } return y; }
向子方法传入任意值,输出y
public static void main(String args[]){ int y=getValue(0); System.out.println(y); } public static int getValue(int x){ int y=0; if(x<1){ y=x; }else if(x>=1 && x<10){ y=2*x-1; }else{ y=3*x-11; } return y; }
结果
0<1,所以y=x,输出正确;
public static void main(String args[]){ int y=getValue(8); System.out.println(y); } public static int getValue(int x){ int y=0; if(x<1){ y=x; }else if(x>=1 && x<10){ y=2*x-1; }else{ y=3*x-11; } return y; }
结果
1<8<10,所以y=2x-1;输出正确;
public static void main(String args[]){ int y=getValue(20); System.out.println(y); } public static int getValue(int x){ int y=0; if(x<1){ y=x; }else if(x>=1 && x<10){ y=2*x-1; }else{ y=3*x-11; } return y; }
结果
20>10,所以y=3x-11;输出正确。