[C language] piecewise function evaluation control output format float accurate to a few decimal places

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

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
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.
insert image description here
Write printf("y=%.2f\n",y);it again, and try it again.
insert image description here
Write it directly printf("y=%f\n",y);, and then test it.
insert image description here
That is to say, y=%.3fthe 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.
insert image description here

Guess you like

Origin blog.csdn.net/qq_44731019/article/details/123569444