编写程序,计算下列分段函数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
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int n;
scanf("%d", &n);
while(n--) {
float x;
scanf("%f", &x);
float y = 0;
if(0 <= x && x < 2) {
y = 2.5 - x;
}
else if(x < 4) {
y = 2 - 1.5 * (x - 3) * (x - 3);
}
else {
y = x / 2 - 1.5;
}
printf("y=%.1f\n", y);
}
return 0;
}