当前位置:网站首页>Su embedded training - Day3

Su embedded training - Day3

2022-07-08 00:13:00 Light chasing rain

One I / O function

1.1 getchar()/putcgar()

1.1.1getchar()

The header file :#include <stdio.h>
Prototype :int getchar(void);
function : Read a character from the terminal
Parameters : nothing
Return value : Characters read from the terminal

#include <stdio.h>
int main(int argc, const char *argv[])
{
	/*int ch;
	ch = getchar();
	printf("ch = %c %d\n",ch,ch);
*/
	int a,b,c;
	a = getchar();
	b = getchar();
	c = getchar();
	printf("a = %c %d\n",a,a);
	printf("b = %c %d\n",b,b);
	printf("c = %c %d\n",c,c);
	
	return 0;
}

1.1.2 putchar

 The header file :#include <stdio.h>
 Prototype :int putchar(int c);

 function : Output a character... To the terminal 
 Parameters :c: Characters to output 
 Return value : Output characters 
#include <stdio.h>

int main(int argc, const char *argv[])
{
	// The parameter is one character 
	putchar('w');
	putchar('\n');
	// Parameter is one ascii
	putchar(97);
	putchar(10);
	
	int a = 'h';
	int b = 10;
	putchar(a);
	putchar(b);
	return 0;
}

1.2 gets()/puts()

1.2.1 gets()

 The header file :#include <stdio.h>
 Prototype :char *gets(char *s);

 function : Read a string from the terminal 
 Parameters :s: Save the contents of the read data , It's usually an array ,char buf[32]
 Return value : Saved string 
#include <stdio.h>

int main(int argc, const char *argv[])
{
	char str[32] = {0};
	gets(str);
	printf("str = %s\n",str);
	return 0;
}

1.2.2 puts()

 The header file :#include <stdio.h>
 Prototype :int puts(const char *s);

 function : Output a string to the terminal 
 Parameters :s: What to output 
 Return value : Number of bytes of the output string 
#include <stdio.h>

int main(int argc, const char *argv[])
{
	//puts The function has its own line feed function 
	puts("hellworld");

	char s[32] = "helloworld";
	puts(s);

	char buf[32] = {0};
	gets(buf);
	puts(buf);
	return 0;
}

3.3 printf()/scanf()

3.3.1 printf()

printf Function is a line buffer function (1024K), Write the content to the buffer first , When certain conditions are met , Will write the content to the corresponding file or stream 
1. Buffer full 
2. There are... Characters written ‘\n’,'\r'
3. call fflush or stdout Refresh buffer manually 
4. call scanf When you want to read data from the buffer , It also flushes the data in the buffer 
5. At the end of the program 
 The header file :#include <stdio.h>
 Prototype :int printf(const char *format, ...);


 function : Output the string to the terminal in the format 
 Parameters :format: Formatted content to output 
     Ordinary character : Original output 
    	 for example :printf("hello world!\n");
      Format specification : %[ Modifier ] Format characters , Used to specify format output 
     	 for example :printf("a = %d\n",a);
      	%d: 32 Bit signed decimal number 
       	%u: 32 Bit unsigned decimal 
        	%o:  octal 
         	%x:  Hexadecimal 
          	%e:  Exponential form 
           %c:  character 
           %s:  character string 
           %%: Output % In itself 
           %p:  Output address 
     Additional formatting characters :
    	#:  Used to output the leading character of octal or hexadecimal 
     	l:  For output long Type or double Data of type 
      	m:  Set the width of the output 
               If the width of the data is greater than or equal to m, It doesn't affect ,
               If the width of the data is less than m, The default right alignment , Fill in the blank in the flat position 
    	0: When the width is set , Default right alignment , Fill in the space on the left 0
      	-: Change right alignment to left alignment 
       	.n: After decimal point n position 
        arg: Variable parameter , There can be , There can be no , There can be more than one 
 Return value : Number of bytes output 
#include <stdio.h>
int main(int argc, const char *argv[])
{
	int num = 256;
	printf("%d%d%d\n",num,num,num);
	//5: Set the width of the output to 5
	printf("%5d%5d%5d\n",num,num,num);
	//0: Align right and fill left 0	
	printf("%05d%05d%05d\n",num,num,num);
	//-: Change right alignment to left alignment 	
	printf("%-5d%-5d%-5d\n",num,num,num);
	//:0 Cannot be used for left alignment 	
	printf("%-05d%-05d%-05d\n",num,num,num);

	float f = 45.45678912345;
	printf("f = %f\n",f);
	//.2: After decimal point 2 position , And it's going to be rounded 
	printf("f = %6.3f\n",f);
	printf("f = %p\n",&f);
	return 0;
}

3.3.2 scanf()

 The header file :#include <stdio.h>
 Prototype : int scanf(const char *format, ...);


 function : Input the specified content from the terminal according to the format 
 Parameters :format: Content with formatted characters 
     Format characters :
    	%d  Shaping data 
     	%f  Floating point data 
      	%c  Character data 
       	%s  String data 
        ...
 Return value : Number of successfully saved content 
#include <stdio.h>

int main(int argc, const char *argv[])
{
	/*
	int num;
	int ret = scanf("%d",&num);
	printf("ret = %d,num = %d\n",ret,num);
	*/
	/*
	char ch;
	scanf("%c",&ch);
	printf("ch = %c %d\n",ch,ch);
	*/
	/*
	char buf[32] = {0};
	//scanf By default, only one string without spaces can be saved 
	scanf("%s",buf);
	// Find the newline character to end the input 
	scanf("%[^\n]",buf);
	printf("buf = %s\n",buf);
	*/
	/*int num;
	scanf("[%d]",&num);
	printf("num = %d\n",num);
	*/
	
	int a,b,c;
	scanf("%d,%d,%d",&a,&b,&c);
	printf("a = %d,b = %d,c = %d\n",a,b,c);
	return 0;
}

3.3.3 scanf Additional characters

m: Set the input width , If the input content exceeds the set width , Only the content of the set width will be saved
: Suppressor , When with The input content of characters in the format of will not be saved to the corresponding variable , Instead, the next one will not take * The contents of the characters in the format of are saved in the previous variables

#include <stdio.h>
int main(int argc, const char *argv[])
{
	/*
	int year,month,day;
	scanf("%2d%2d%2d",&year,&month,&day);
	printf("%d/%d/%d\n",year,month,day);
	
	char buf[32] = {0};
	scanf("%5s",buf);
	printf("buf = %s\n",buf);
	*/

	int a,b,c;
	scanf("%d %*d %d %*d %d",&a,&b,&c);
	printf("a = %d,b = %d,c = %d\n",a,b,c);
	return 0;
}

3.3.4 scanf Input multiple contents and garbage character processing

#include <stdio.h>
int main(int argc, const char *argv[])
{
#if 0
	int a,b,c;
	scanf("%d %d %d",&a,&b,&c);
	printf("a = %d,b = %d,c = %d\n",a,b,c);
#endif
#if 0
	char a,b,c;
	scanf("%c%c%c",&a,&b,&c);
	printf("a = %c,b = %c,c = %c\n",a,b,c);
#endif
	/*  One scanf Deal with garbage characters  */
// Method 1: Use suppressor 
/*	char a,b,c;
	scanf("%c%*c%c%*c%c",&a,&b,&c);
	printf("a = %c,b = %c,c = %c\n",a,b,c);*/
// Method 2: Use spaces to separate 
	/*char a,b,c;
	scanf("%c %c %c",&a,&b,&c);
	printf("a = %c,b = %c,c = %c\n",a,b,c);*/
	/* Multiple scanf Deal with garbage characters */
	int id;
	char name[32];
	char sex;
	int score;
	char bg;
	/*
	printf(" Please enter the student number :");
	scanf("%d",&id);
	printf(" Please enter a name :");
	scanf("%s",name);
	printf(" Please enter gender :");
	scanf("%c",&sex);
	printf(" Please enter the score :");
	scanf("%d",&score);
	printf(" Please enter age :");
	scanf("%d",&age);
	*/

#if 0  // Use suppressor 
	printf(" Please enter the student number :");
	scanf("%d",&id);
	printf(" Please enter a name :");
	scanf("%s",name);
	printf(" Please enter gender :");
	scanf("%*c%c",&sex);
	printf(" Please enter the score :");
	scanf("%d",&score);
	printf(" Please enter whether you have a girlfriend :");
	scanf("%*c%c",&bg);
#endif
#if 0  // Use getchar
	printf(" Please enter the student number :");
	scanf("%d",&id);
	printf(" Please enter a name :");
	scanf("%s",name);
	getchar();
	printf(" Please enter gender :");
	scanf("%c",&sex);
	printf(" Please enter the score :");
	scanf("%d",&score);
	getchar();
	printf(" Please enter whether you have a girlfriend :");
	scanf("%c",&bg);
#endif
//  Use spaces 
	printf(" Please enter the student number :");
	scanf("%d",&id);
	printf(" Please enter a name :");
	scanf("%s",name);
	printf(" Please enter gender :");
	scanf(" %c",&sex);
	printf(" Please enter the score :");
	scanf("%d",&score);
	printf(" Please enter whether you have a girlfriend :");
	scanf(" %c",&bg);
	return 0;
}

Two Control statement

2.1 Concept

The control statement mainly solves the problem that some code needs to be executed , Some code does not execute , Or the same code needs to be executed many times .
classification :

 Branch statement :
if...esle
switch...case...
 Loop statement :
goto
while
do...while...
for
 Auxiliary control keywords :
goto
break
continue
return

2.2 if…else sentence

2.2.1 if The form of the statement

if( expression )
{
     Sentence block 
}
 or :
if( expression )
{
 	 Sentence block 1   
}
else
{
     Sentence block 2
}
if( expression 1)
{ Sentence block 1}
else if( expression 2)
{ Sentence block 2}
else
{ Sentence block 3}
 matters needing attention :
    1.if The expression of is not 0 It's true 
        if(0)  // false 
        if(1)  // really 
        if(0.00000001)  // really 
        if(a)---->if(a != 0)
        if(!a) ---->if(a == 0)
        if(a = 0)  // false 
        if(a = 1) // really 
    2.if perhaps else There is only one code after the statement , Can not add {}, But generally in order not to produce ambiguity , Better add 
    3.else  Cannot be followed by an expression 
    if and else Only one can be executed 
    else Not to be used alone , and else Default and the nearest one if relation .
    if( expression 1)
    {
    	if( expression 2)
     	{
                
      	}
    }
 

2.2.2 practice : toggle case

Enter a character at the terminal , If it's a capital letter , Convert it to lowercase letters , If it's lowercase , Turn it into capital letters , And enter the , If it is a character number , Convert it to digital output .
‘h’---->‘H’
‘H’---->‘h’
‘6’----->6

#include <stdio.h>

int main()
{
	char a;
	a = getchar();
	
	if(a >= 'a' && a <= 'z')
	{
		a = a - ('a' - 'A');
		putchar(a);
	}
	else if (a >= 'A' && a <= 'Z')
	{
		a = a + ('a' - 'A'); 
		putchar(a);
	}
	else if (a >= '0' && a <= '9')
	{
		printf("%d\n",a - 48);
	}
	else
	{
		printf("error");
	}
	return 0;
 } 

2.3 swich…case sentence

switch Statement and if The sentence is the same , It's also a branch statement , It's just switch Statement is used when there are too many conditions

2.3.1 Format

switch( Variable or variable expression )
{
    case  Constant or constant expression 1:
    	 Sentence block 1;
     	//break;
    case  Constant or constant expression 2:
    	 Sentence block 2;
     	break;
      case  Constant or constant expression 3:
		 Sentence block 3;
 		break;   
     case  Constant or constant expression 4:
  	 	 Sentence block 4;
   	break;  
    defalut:
    	 Sentence block n;
     	break;           
}
#include <stdio.h>

int main(int argc, const char *argv[])
{
	int num;
	printf("***1. register  2. Sign in  3. sign out ***\n");
	printf(">>>> ");
	scanf("%d",&num);
	switch(num)
	{
	case 1:
		printf(" Performing registration \n");
		break;
	case 2:
		printf(" Performing login operation \n");
		break;
	case 3:
		printf(" Exiting , One moment please ..\n");
		break;
	default:
		printf(" Your input is wrong , Please re-enter \n");
		break;
	}
	return 0;
}

2.3.2 matters needing attention

switch The following expression is a variable or variable expression 
case It can only be a constant or a constant expression , And this expression cannot be a range , The value of each constant expression must be different , Otherwise, there will be contradictions ,
case If there are multiple statements later , Don't have to add {}
switch Only integer data and character data can be judged in the statement , Cannot be floating point or string 
default You don't need to add break
break Mainly to end switch sentence , If not , From specified case Execute all statement blocks down after the statement , Until I met break until .

3、 ... and Loop statement

We're writing code , Often, some code may be executed many times , So for simplicity , You can do this through a loop , So readable , Logic will be better

3.1 while loop

3.1.1 Format

while( expression )
{
     Sentence block 
}
 matters needing attention : Cyclic conditions cannot always be true , There must be a condition for the end of the cycle , If you cycle forever , Call it a dead cycle , for example :while(1);

3.1.2 Simple use of recycling

#include <stdio.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
	/*
	while(1)
	{
		printf("helloworld\n");
		sleep(1);
	}*/
	int i = 5;
	while(i--)
	{
		printf("helloworld\n");
	}
	// The programmer 40W, housing price 200W,10%, If you don't raise your salary , No loans , Ask how many years you can buy a house ?
	int year = 0,sum = 0,price = 200;
	while(1)
	{
		year++;
		sum += 40;
		price += price*0.1;
		if(sum >= price)
		{
			printf(" The first %d Buy a house in \n",year);
			break;
		}
		printf(" The first %d I can't afford to buy a house in \n",year);

	}
	return 0;
}

3.1.3 do…while… Use

#include <stdio.h>

int main(int argc, char *argv[])
{
	//do..while The loop executes once first , Then judge , So whether the expression is false or not , It's all done once 
	do
	{
		printf("hello world!\n");
	}while(0);
	return 0;
}

3.2 for loop

3.2.1 Format

for( expression 1; expression 2; expression 3)
{
     Sentence block ; 	   
}
 Execution order : Execute expression first 1, Execute the expression after execution 2, If the expression 2 It's true , Then execute the statement block , After executing the statement block , Then execute the expression 3, And then again 
 Execute expression 2, If the expression 2 It's true , Then execute the statement block , And so on , Until the expression 2 When it is false , The loop ends 

Be careful :for Circulation and while Loops are general

int i = 0;
while(i < 10)
{
 	i++;   
}
for(i = 0; i < 10;i++)
{
...
}

3.2.2 for Circular considerations

for( expression 1; expression 2; expression 3)
{
     Sentence block 
}
1. expression 1: It mainly assigns initial values to variables to be counted , The whole loop is executed only once , You can also omit not to write ,
2. No matter which expression is omitted , You can't lose the semicolon 
3. expression 2 The main thing is to judge the conditions , If the condition is true, execute the statement block , The condition is that the false loop ends , If you omit the expression 2 Don't write , It's going to create a dead cycle 
for(i = 0 ;;i++)
4. expression 3 It is to change the value of the count variable and thus affect the number of cycles , If you omit the expression 3 Don't write , It's going to create a dead cycle , Of course, you can put expression three in a statement block 
 It's OK, too 
 Dead cycle :for(;;);

3.2.3 for The use of recycling

#include <stdio.h>
int main(int argc, const char *argv[])
{
	int i;
	/*
	for(i = 0,printf("i = %d\n",i);i < 5,printf("i = %d\n",i);i++,printf("i = %d\n",i))
	{
		printf("hello world!\n");
	}*/
	int j;
	for(j = 0 ;j < 3;j++)
	{
		for(i = 0 ; i < 5;i++)
		{
			if(1 == i)
			{
				continue;  // End this cycle , So let's go to the next loop 
			//	break;     // End this cycle 
			}
			printf("hello world! %d\n",i);
		}
		printf("hello nanjing\n");
	}
	return 0;
}

3.2.4 Print 100-1000 The number of all daffodils within

Narcissistic number : It refers to the sum of the cubes of each three digit number is equal to this number , Then this number is called narcissus number
num = The cube of a bit + The cube of ten + A hundred digit cube

Four Auxiliary control keywords

4.1 goto

goto It is mainly used to jump within a function , You can jump to any position of the current function
Be careful : It is not recommended to use too much , Readability , Logic will become worse

#include <stdio.h>
int main(int argc, const char *argv[])
{
#if 0
	int num = 100;
	printf("111111111111111111111111\n");
	goto NEXT;
	printf("hello world!\n");
	num = 888;
	printf("hello nanjing");
NEXT:
	printf("hello beijing\n");
	printf("num = %d\n",num);
	printf("222222222222222222222222222");
#endif
	int i = 0;
TEMP:
	printf("hello world\n");
	i++;
	if(i <= 9)
	{
		goto TEMP;
	}
	return 0;
}

4.2 break;

break stay switch Statement is mainly used to end the specified statement block
break Mainly used in loop statements , The function is to end this cycle
Be careful :break In addition to the switch Outside the sentence , Other places can only be used in circulation

4.3 continue

continue Can only be used in a loop , Means to exit this cycle , Run next cycle

4.4 return

#include <stdio.h>

int main(int argc, const char *argv[])
{
	int i;
	for(i = 1;i <= 10;i++)
	{
		if(i == 5)
		{
			return i;
		}
		printf("i = %d\n",i);
	}
	printf("hello world!\n");
	return 0;
}

Homework

practice : Two number operations
Enter two numbers , Then enter the operator ( Add, subtract, multiply and divide ), Realize the operation between two numbers

#include <stdio.h>

int main()
{
	int num_1,num_2,result;
	char run_num; 
	printf(" Enter the two numbers to be calculated , And separated by commas :\n"); 
	scanf("%d,%d",&num_1,&num_2);
	printf(" Input operator , Such as *,/,+,-\n");
	getchar();
	scanf("%c",&run_num);
	
	switch(run_num)
	{
		case '+':
		{
			result = num_1 + num_2;
			break;
		}
		case '-':
		{
			result = num_1 - num_2;
			break;	
		}
		case '*':
		{
			result = num_1 * num_2;
			break;	
		}
		case '/':
		{
			result = num_1 / num_2;
			break;	
		}
		default:
			{
				printf("error!");
			}
	} 
	printf("%d %c %d = %d",num_1,run_num,num_2,result);
	 
	return 0;
}

Homework 2: Write a program to calculate the rise

 Every parent cares about the height of their children when they grow up , According to the knowledge of physiological health and mathematical statistics, it is shown that ,
 There are genetic factors that affect the height of children as adults 、 Eating habits and physical exercise . The height of a child as an adult is the same as that of his father 
​	 The height of a mother is closely related to her gender .
​	 set up faHeight For his father's height ,moHeight For the height of his mother ,
  The height prediction formula is :  
​	 Male adult height  = (faHeight + moHeight) * 0.54(cm) 
​	 Female adult height  = (faHeight * 0.923 + moHeight) / 2(cm)  
​	 Besides , If you love physical exercise , Then you can increase your height 2%
​	 If you have good healthy eating habits , Then you can increase your height 1.5%
 Procedural requirements : Father's height and mother's height 、 The gender of the child 、 Do you like physical exercise and have good hygiene 
​	 Eating habits are also entered from the keyboard , The final output is the predicted height .   Tips : How to input the child's gender , Available on the screen 
​	 Give hints “ Please enter the gender of the child ( Boy input M, Girl input F):”, And then through if Sentence to judge from the keyboard 
​	 The character entered is M still F. Whether you like physical exercise can also be achieved in a similar way .
#include <stdio.h>

int func(int faheight,int moheight,char sex,char like_sports,char health_diet)
{
    int result;

    if(sex == 'M')
    {
        if(like_sports == 'Y')
        {
            if(health_diet == 'Y')
            {
                result = (faheight + moheight) * 0.54 * 1.02 * 1.015;
            }
            else
            {
                result = (faheight + moheight) * 0.54 * 1.02;
            }
            
        }
        else
        {
            if(health_diet == 'Y')
            {
                result = (faheight + moheight) * 0.54 * 1.015;
            }
            else
            {
                result = (faheight + moheight) * 0.54;
            } 
        }
        
    }
    else
    {
        if(like_sports == 'Y')
        {
            if(health_diet == 'Y')
            {
                result = (faheight * 0.923 + moheight) / 2 * 1.02 * 1.015;
            }
            else
            {
                result = (faheight * 0.923 + moheight) / 2 * 1.02;
            }
            
        }
        else
        {
            if(health_diet == 'Y')
            {
                result = (faheight * 0.923 + moheight) / 2 * 1.015;
            }
            else
            {
                result = (faheight * 0.923 + moheight) / 2;
            }
        }
    }
    

    return result;
}

int main(int argc, char const *argv[])
{
    int faheight,moheight;
    char sex,like_sports,health_diet;

    printf("put in faheigeht(cm) and moheight(cm):\n");
    scanf("%d %d",&faheight,&moheight);
    getchar();

    printf("Male or Female [M/F]\n");
    sex = getchar();
    getchar();

    printf("Whether he/she likes sports or not [Y/N]\n");
    like_sports = getchar();
    getchar();

    printf("Whether he/she has health diet or not [Y/N]\n");
    like_sports = getchar();
    getchar();

    int result = func(faheight,moheight,sex,like_sports,health_diet);

    printf("Height is %d\n",result);

    return 0;
}

Homework 3: Enter a date , The output current date is the day of the year

2021 year 1 month 10 The day is 2021 In the first 10 God 
2021 year 2 month 10 The day is 2021 In the first 31+10=41 God 
2021 year 3 month 10 The day is 2021 In the first 31+28+10=69 God 
 Leap year and ordinary year 2 The days of the month are different 
 The days of each month are different 
 The input date must also meet the actual situation 
 Not meeting the conditions , have access to return -1; End the whole program 
#include <stdio.h>

int cor(int flag,int month,int day)
{
    int arri[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if(flag == 0)
    {
        arri[1] = 29;
    }
    if(month > 12 || month < 1)
    {
        return -1;
    }

    if(arri[month - 1] < day)
    {
        return -1;
    }

}

int cal(int year,int month,int day)
{
    int sum_day,flag;
    flag = 1;
    int arr[12] = {0,30,28,31,30,31,30,31,31,30,31,30};
    if(year >= 2022 || year <= 0)
    {
        return -1;
    }
    if(((year % 100 == 0) && ((year / 100) % 4 == 0)) || (year % 4 == 0))
    {
        flag = 0;
        arr[2] = 29;
    }
    if(cor(flag,month,day) == -1)
    {
        return -1;
    }
    for(int i = 0; i < month; i++)
    {
        sum_day += arr[month];
    }
    sum_day += day;
    return sum_day;
}

int main(int argc, char const *argv[])
{
    int year,month,day,sum_day;

    printf("year = \n");
    scanf("%d",&year);
    printf("month = \n");
    scanf("%d",&month);
    printf("day = \n");
    scanf("%d",&day);

    sum_day = cal(year,month,day);

    if(sum_day == -1)
    {
        printf("error!\n");
    }
    else
    {
        printf("sum days = %d\n",sum_day);       
    }
    
    return 0;
}

原网站

版权声明
本文为[Light chasing rain]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130551478109.html