The case is as follows
//分段函数求值
#include <stdio.h>
//#include <math.h>
int main()
{
float x,y;
printf("请输入x的值:");
scanf("%f",&x);
printf("\n");
if(x<1)
{
y=x;
}
else if(x>=1&&x<10)
{
y=2*x-1;
}
else if(x>=10)
{
y=3*x-11;
}
printf("y=%.3f\n",y);
return 0;
}
Test output
The key point is that for the judgment of the if condition, pay attention and should be expressed as &&
, not just write a &.
Another interesting point is the control over the format of the output result. Try changing the output format below.
Write printf("y=%.5f\n",y);
it, test it out.
Write printf("y=%.2f\n",y);
it again, and try it again.
Write it directly printf("y=%f\n",y);
, and then test it.
That is to say, y=%.3f
the output format is accurate to the third decimal place. If .3 is not added, the default is to be accurate to 6 decimal places. Both double and float are accurate to 6 decimal places by default.
Then the same can also be written with higher precision: printf("y=%.8f\n",y);
but the meaning may not be large.