c language variable of type int input a character error

 

Encountered a small problem C language today, is to write a simple calculator, the definition of one percent three variables f% c% f, and this can make 2 + 3,2-3 constantly enter and enter the "OFF" jump cycle calculator function, an error will occur;

Error sample code is as follows:

#include<stdio.h>

int main ()
{
	float x,y;
	the char;
	while(1)
	{	
		scanf("%f%c%f",&x,&z,&y);
		if(z=='+') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x+y); }
		else if(z=='-') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x-y); }
		else if(z=='*') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x*y); }
		else if(z=='/') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x/y); }	
		else break;
	}

}

  

 

It will continue the implementation of the results of the previous step, into an infinite loop. . . .

After Find items found an error because the C language, as you enter a number, the system will but if you enter characters, the system will fail to read from the buffer to read out the data in this format, this character or stay in buffer, and then read the system, or a read failure, this character will always remain in the buffer, the reading system will never finish  when used int, float variable is defined, using scanf ( "% d") function for data input If a non-numeric key is pressed, the scanf () function returns an error, i.e. d == 0;

Using this feature, we slightly modify the program, we can achieve the cycle to calculate the input and exit function when entering characters OFF;

 

The edited code is as follows:

#include<stdio.h>
int main ()
{
	int a=1,i=0,o=0;
	float x,y;
	the char;
	int d;
	while(1)
	{	
		d=scanf("%f%c%f",&x,&z,&y); 
		if(d==0){printf("退出!");break;};
		if(z=='+') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x+y); }
		else if(z=='-') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x-y); }
		else if(z=='*') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x*y); }
		else if(z=='/') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x/y); }	
	}
// write a line of code in the method less 
//	while(d=scanf("%f%c%f",&x,&z,&y))
//	{	
//		if(d==0){printf("退出!");break;};
//		if(z=='+') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x+y); }
//		else if(z=='-') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x-y); }
//		else if(z=='*') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x*y); }
//		else if(z=='/') {printf("%.2f%c%.2f=%.2f\n",x,z,y,x/y); }	
//	}
}  

 

 

 

When receiving the scanf string, we define a variable to determine whether d out of the loop can! (Problem solved! Happy to sleep ~)

Guess you like

Origin www.cnblogs.com/ma1998/p/12081862.html