当前位置:网站首页>Introduction and C series input and output programming language 3

Introduction and C series input and output programming language 3

2021-03-30 18:04:24 CuterCorley

From a procedural point of view , Programs can be divided into three basic structures , That is, sequential structure 、 Branching structure 、 Loop structure , These three basic structures can make up all kinds of complex programs ,C Language provides a variety of statements to implement these program structures . meanwhile C The input and output functions provided by the language are IO Provides a convenient tool .

One 、C Statement introduction

1.C Basic statement

C The executive part of a program is made up of statements , The function of the program is also realized by the execution statement .C Sentences can be divided into the following five categories :

  • Expression statement expression statement : An expression statement is an expression plus a semicolon ; form . Its general form is expression ;, Executing an expression statement is Evaluate the value of an expression . for example :
      x=y+z;  //  Assignment statement   y+z;   //  Addition statement , But the result of the calculation cannot be preserved , No practical significance   i++;    //  Self increasing 1 sentence ,i Value increase 1
  • Function call statement function call statement is defined by function name 、 Actual parameters plus semicolon ; form . Its general form is Function name ( Table of actual parameters );. To execute a function statement is to call the function body and assign the actual parameters to the formal parameters in the function definition , Then execute the statement in the body of the called function , Find function value . for example :
      printf("C Program"); // Call library function , Output string 
  • Control statements control statements are used to control the flow of a program , In order to realize the various structures of the program , They are made up of specific statement definers .C There are nine control statements in language , It can be divided into three categories :
    • Conditional statements :if sentence 、switch sentence ;
    • Loop statement :do while sentence 、while sentence 、for sentence ;
    • Turn to statement :break sentence 、goto sentence 、continue sentence 、return sentence .
  • Compound statements use parentheses for multiple statements {} A statement formed by enclosing is called a compound statement . In a program, a compound statement should be regarded as a single statement , Instead of multiple statements . for example :
      {       x=y+z;      a=b+c;      printf(“%d%d”,x,a);  }
    This is a compound statement . Each statement in a compound statement must be signed with a semicolon ; ending , stay Curly braces } You can't add a semicolon .
  • Empty statements have only semicolons ; A statement that is composed of is called an empty statement , That is, a statement that does not execute anything , It can be used as empty loop body in program . for example :
      while(getchar()!='\n')  {      ;  }
    The loop body here is an empty statement , The function is to re-enter as long as the character entered from the keyboard is not carriage return .

2. Assignment statement

An assignment statement is an expression statement composed of an assignment expression and a semicolon . Its general form is Variable = expression ;.

The functions and characteristics of assignment statements are the same as those of assignment expressions , It's one of the most used statements in a program . In the use of assignment statements, we need to pay attention to the following points :

  • Due to the fact that = The expression on the right can also be another assignment expression , therefore , form Variable =( Variable = expression ); Is established , So as to form a nested situation , The general form after its expansion is Variable = Variable =…= expression ;. for example :

      a=b=c=d=e=5;

    According to the right associativity of the assignment operator , So it's actually equivalent to :

      e=5;  d=e;  c=d;  b=c;  a=b;
  • In variable description, there is a difference between assigning initial value to variable and assigning statement : Assigning initial values to variables is part of the description of variables , The variables with initial values must be separated from other variables of the same kind by commas , The assignment statement must end with a semicolon . for example :

      int a=5,b,c;
  • In the variable description , It is not allowed to continuously assign initial values to multiple variables . Such as int a=b=c=5; It's wrong. , It must be written as int a=5, b=5, c=5;, The assignment statement allows continuous assignment .

  • The difference between an assignment expression and an assignment statement is as follows : An assignment expression is an expression , It can appear anywhere an expression is allowed to appear , The assignment statement cannot . for example , sentence if((x=y+5)>0) z=x; It's legal. , The meaning is if the expression x=y+5 Greater than 0 be z=x, And the statement if((x=y+5;)>0) z=x; It's illegal. , because x=y+5; Is the statement , Cannot appear in an expression .

Two 、 Data input and output

I / O is Take the computer as the main body In terms of the , Here is mainly the statement to output data to the standard output device display . stay C In language , All the data input 、 The output is done by library functions , So it's all function statements . In the use of C Library functions , To use the precompile command #include take About header files Include in the source file . When using standard input and output library functions, you need to use stdio.h file , So there should be a precompile command at the beginning of the source file #include< stdio.h > or #include "stdio.h", among ,stdio yes standard input & output It means . in consideration of printf and scanf Functions are used frequently , Some compilers allow you to use these two functions without adding #include< stdio.h > or #include "stdio.h". In general , The source file of the system is in angle brackets <>, Double quotation marks for custom files "".

1.putchar function ( Character output function )

putchar The function is Character output function , Its function is on the monitor Output single character . Its general form is :

putchar( Character variables );

for example :

putchar('A');    //  Output capital letters Aputchar(x);      //  Output character variables x Value putchar('\101'); //  The output characters Aputchar('\n');   //  Line break 

Yes Control characters Perform control functions , Not on the screen .

Use putchar The function must be preceded by a file containing the command #include <stdio.h> or #include "stdio.h".

putchar The exercises are as follows :

#include <stdio.h>int main(){    char a = 'B', b = 'o', c = 'k';    putchar(a);putchar(b);putchar(b);putchar(c);putchar('\t');    putchar(a);putchar(b);    putchar('\n');    putchar(b);putchar(c);    return 0;} 

Print :

Book    Book

2.getchar function ( Keyboard input function )

getchar The function's function is from the keyboard Enter a character . Its general form is :

getchar();

The input character is usually assigned to a character variable , Constitute an assignment statement , Such as :

char c;c = getchar();

getchar The exercises are as follows :

#include <stdio.h>int main(){    char c;    printf("input a character:\n");    c = getchar();    putchar(c);    putchar('\n');    return 0;} 

as follows :c language putchar getchar

3. Format output printf

printf Functions are called format output functions , The last letter of the keyword f That is to say Format (format) The meaning of , Its function is according to the user specified format , Display the specified data on the screen .

printf The general form of a function call

printf Function is a Standard library functions , Its function prototype is in the header file stdio.h in . As an exception , Using a few compilers like VC The compiler compiles with printf Function may not contain stdio.h file .

printf The general form of a function call is :

printf(" Format control string ",  Output table columns );

The format control string is used to specify the output format , It can be composed of format string and non format string . The format string is in % Starting string , stay % Followed by various format characters , To illustrate the type of output data 、 form 、 length 、 Decimal places, etc . Such as :

  • %d Represents the decimal integer output ;
  • %ld Represents long integer output in decimal system ;
  • %c It means output according to character type, etc .

Unformatted strings are printed as is when they are output , Play the role of prompt in the display . Each output item is given in the output table column , The format string and each output item are required to be in quantity 、 One to one correspondence in type and order .

The exercises are as follows :

#include <stdio.h>int main(){    int a = 71, b = 72;    printf("%d %d\n", a, b);    printf("%ld, %ld\n", a, b);    printf("%c %c\n", a, b);    printf("a=%d, b=%d", a, b);    return 0;} 

Print :

71 7271, 72G Ha=71, b=72

In this case, four outputs a、b Value , But because the format control string is different , The output is also different . for the first time printf Statement format control string , Two format strings %d With a space between ( Unformatted characters ), So the output a、b There is a space between the values ; The second time printf The non format character comma is added to the statement format control string , So the output a、b A comma is added between the values ; third time printf The statement format control string is required to be output in character type a、b value ; The fourth time printf The statement format control string adds a non format string to prompt the output result .

Format string

(1) The type character of the format string is used to indicate the type of output data , The format and meaning are as follows :printf Format string type (2) The logo and its meaning are as follows :printf Format string flag (3) The minimum width of output is expressed as the minimum number of digits in decimal integer . If the actual number of digits is more than the defined width , Then output according to the actual number of digits , If the actual number of digits is less than the defined width, a space or 0.(4) The precision format is marked with a dot . start , Followed by a decimal integer . The meaning of this item is : If the output number , Is the number of decimal places ; If the output is a character , Indicates the number of output characters ; If the actual number of digits is greater than the precision number defined , Then cut off the excess part .(5) The length format is h、l Two kinds of ,h It means output as short integer ,l It means output by long integer .

An example of a format string is as follows :

#include <stdio.h>int main(){    int a = 15;    float b = 123.7654321;    double c = 12345678.87654321;     char d = 't';    printf("a=%d,%5d,%o,%x\n", a, a, a, a);    printf("b=%f,%lf,%5.4lf,%e\n", b, b, b, b);    printf("c=%lf,%f,%8.4lf\n", c, c, c);    printf("d=%c,%8c\n", d, d);    return 0;} 

Print :

a=15,   15,17,fb=123.765434,123.765434,123.7654,1.237654e+002c=12345678.876543,12345678.876543,12345678.8765d=t,       t

Use printf Function also pay attention to the evaluation order in the output table column . Different compilation systems are not necessarily the same , From left to right , It can also be from right to left .

One printf() Statements and multiple printf() The difference between sentences is as follows :

#include <stdio.h>int main(){    int i = 8;    printf(" for the first time :\n%d\n%d\n%d\n%d\n%d\n%d\n", ++i, --i, i++, i--, -i++, -i--);    i = 8;    printf(" The second time :\n%d\n", ++i);    printf("%d\n", --i);    printf("%d\n", i++);    printf("%d\n", i--);    printf("%d\n", -i++);    printf("%d\n", -i--);    return 0;} 

Print :

 for the first time :8878-7-8 The second time :9889-8-9

The difference between the two is to use one printf Sentence or multiple printf Statement output , It's different from the results ; obviously , The second result is easier to understand .

4. Format input scanf

scanf Functions are called format input functions , That is to say, input the data into the specified variables from the keyboard according to the format specified by the user .

scanf The general form of a function

scanf Function is a standard library function , Its function prototype is in The header file stdio.h in . And printf The same function , In a few compilers, the use of scanf Function does not contain stdio.h file .scanf The general form of the function is :

scanf(" Format control string ",  Address table column );

among , The function of format control string and printf The same function , but Can't display unformatted strings , That is, the prompt string cannot be displayed . The address of each variable is given in the address table column , Address by Address operators & Plus variable names . for example &a, &b Each represents a variable a And variables b The address of , This address is given by the compiler system in memory a、b The address of the variable assignment . stay C In language , Using the concept of address , It's different from other languages ,C Language allows control of addresses in memory , That is, you can control the bottom of the system .

We should distinguish the value of a variable from the address of a variable , The address of the variable is C The compiler system allocates , Users don't have to care about the specific address . Assign a value to a variable in an assignment expression , Such as a = 567; in ,a Variable name ,567 Is the value of the variable ,&a It's a variable. a The address of .

But to the left of the assignment number is the variable name a, Can't write address , and scanf In essence, functions assign values to variables , But you need to write the address of the variable , Such as &a. The two have different meanings ,& It's an address operator ,&a It's an expression , Its function is to find the address of the variable .

The exercises are as follows :

#include <stdio.h>int main(){    int a, b, c;    printf("Input a, b, c: \n");    scanf("%d%d%d", &a, &b, &c);    printf("a=%d, b=%d, c=%d\n", a, b, c);    return 0;} 

Print :

Input a, b, c:12 34 56a=12, b=34, c=56

You can see , If there are multiple inputs , You need to split different inputs , Otherwise, the waiting will be blocked , Generally, you can use space or enter ( Line break ) Separate .

Format string

The general form of the format string is :

%[*][ Enter the data width ][ length ] type ;

There are square brackets [] Is any option . The significance of each item is as follows :(1) Type represents the type of input data , Its format and meaning are as follows :scanf Format string type (2) Character to represent the input item , The corresponding variable is not assigned after reading , That is to skip the input value . Such as `scanf("%d %d %d", &a, &b); in , When the input 1 2 3 when , hold 1 give a,2 To be skipped ,3 give b.(3) Width specifies the width of the input as a decimal integer ( The number of characters ). Such as scanf("%5d", &a);, Input 12345678, Only 12345 Assign variable a, The rest is cut off ; and scanf("%4d%4d", &a, &b);`, Input 12345678, Then we will 1234 give a、5678 give b.(4) The length format is l and h,l Represents the input of long integer data (%ld) And double precision floating point numbers (%lf),h Represents the input of short integer data .

Use scanf Functions need to pay attention to the following :(1)scanf There is no precision control in the function , Such as scanf("%5.2f",&a); It's illegal. , You cannot attempt to enter a decimal as 2 The real number of bits .(2)scanf Variable address is required in , If you give a variable name, there will be an error , Such as scanf("%d",a); It's illegal. , Should be changed to scnaf("%d",&a);.(3) When inputting multiple numerical data , If there is no non format character in the format control string as the interval between the input data, the space can be used 、TAB Or enter to make an interval .C The compiler encountered a space 、TAB、 Carriage return or illegal data ( If yes %d Input 12A when ,A It's illegal data ) The data is considered to be over .(4) In the input Character data when , If there are no non format characters in the format control string , All the characters entered are considered to be valid . for example scanf("%c%c%c",&a,&b,&c);, Input d e f, Then put 'd' give a, ' ' give b,'e' give c, Only if the input is def when , To put 'd' be endowed with a,'e' give b,'f' give c; If you add spaces as intervals in the format control , Such as scanf ("%c %c %c",&a,&b,&c);, Space can be added between the data when input .

Test the following :

#include <stdio.h>int main(){    char a, b;    printf("Input character a, b: \n");    scanf("%c%c", &a, &b);    printf("a=%c, b=%c\n",a, b);    return 0;} 

Print :

Input character a, b:a ba=a, b=

obviously , When you enter a space , Because a space is also a character , therefore b Is the space ' '. If you want to enter spaces between characters, you can also receive them separately , Need to be in scanf() When you pass in a formatted string, you also add spaces , Such as scanf("%c %c", &a, &b);, At this time, there are spaces between the input data, and you can also receive the characters you want to input . If a、b When the variable is an integer or other type , There is no such thing .(5) If there is an unformatted character in the format control string, the unformatted character should also be input . for example scanf("%d,%d,%d",&a,&b,&c);, The non format character is used , Make a space , So the input should be 5,6,7; And so on scanf("a=%d,b=%d,c=%d",&a,&b,&c);, The input should be a=5,b=6,c=7.(6) If the input data is inconsistent with the output type , Although the compiler can pass , But the result is not right .

Test the following :

#include <stdio.h>int main(){    int a;    printf("Input a number:\n");    scanf("%d", &a);    printf("%ld\n", a);    return 0;}

Print :

Input a number:98765432101286608618

Because the input data type is integer , The format string of the output statement is long , So the output is not consistent with the input data .

practice -- Enter three lowercase letters , Output its ASCII Code and corresponding capital letters :

#include <stdio.h>int main(){    char a, b, c;    printf("Input character a, b, c:\n");    scanf("%c %c %c", &a, &b, &c);    printf("%d, %d, %d\n%c, %c, %c", a, b, c, a-32, b-32, c-32);        return 0;}

Print :

Input character a, b, c:a h o97, 104, 111A, H, O

practice -- Output various types of byte length :

#include <stdio.h>int main(){    int a;    long b;    float f;    double d;    char c;    printf("int:%d\nlong:%d\nfloat:%d\ndouble:%d\nchar:%d\n", sizeof(a), sizeof(b), sizeof(f), sizeof(d), sizeof(c));        return 0;}

Print :

int:4long:4float:4double:8char:1

obviously , You can get the size of various types in the current compilation environment .

practice -- Find triangle area : Enter the length of the three sides of the triangle , Find triangle area : The three sides of a triangle are known a,b,c, Then the area formula of the triangle is : Triangle area among s = (a+b+c)/2.

The code example is as follows :

#include <stdio.h>#include <math.h>int main(){    double a, b, c, s, area;    scanf("%lf,%lf,%lf", &a, &b, &c);    s = 1.0 / 2 * (a + b + c);    area = sqrt(s * (s - a) * (s - b) * (s - c));    printf("a = %7.2g, b = % 7.2g, c = %7.2g, s = %7.2g\n", a, b, c, s);    printf("area = %7.2f\n", area);    return 0;}

Print :

3,4,5a =       3, b =       4, c =       5, s =       6area =    6.00

obviously , In the input 3 When the edges make sense , You can calculate the area of the triangle ;%g It depends on the number Automatic selection %f or %e,7.2 The width of the field is 7 Characters , After the decimal point is 2 A digital .

practice -- Find the root of a quadratic equation : Solving quadratic equations The code is as follows :

#include <stdio.h>#include <math.h>int main(){    double a, b, c, x1, x2, delta, p, q;    scanf("a=%lf, b=%lf, c=%lf", &a, &b, &c);    delta = b * b - 4 * a * c;    p = -b / (2 * a);    q = sqrt(delta) / (2 * a);    x1 = p + q;    x2 = p - q;    printf("\nx1=%5.2lf\nx2=%5.2lf\n", x1, x2);            return 0;}

Print :

a=1, b=-2, c=1x1= 1.00x2= 1.00

this paper First text From the blog column C Language learning , Forwarded by me to https://www.helloworld.net/p/OJyTGeiALU2D, Other platforms are infringing , Clickable https://blog.csdn.net/CUFEECR/article/details/105604811 Look at the original , You can also click https://blog.csdn.net/CUFEECR Browse more quality original content .

 Preview

版权声明
本文为[CuterCorley]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/03/20210325211859365o.html