编写程序,计算下列分段函数y=f(x)的值。
当 0<= x <2,y= -x+2.5;
当 2<= x <4,y=2-1.5(x-3)(x-3);
当 4<= x <6,y=x/2-1.5;
当 2<= x <4,y=2-1.5(x-3)(x-3);
当 4<= x <6,y=x/2-1.5;
输入第一行为整数m表示样例数,接下来有m行每行一个整数x。
输出m行分别表示对应的y值,保留小数点后一位小数。
2 1 3
y=1.5 y=2.0
import java.text.DecimalFormat; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); for (int i = 0; i < m; i++) { double x = scanner.nextDouble(); DecimalFormat f = new DecimalFormat("0.0"); if (x>=0&&x<2) System.out.println("y="+f.format(-x+2.5)); else if (x>=2&&x<4) System.out.println("y="+f.format(2-1.5*(x-3)*(x-3))); else if (x>=4&&x<6) System.out.println("y="+f.format(x/2-1.5)); } } }