Preparation of program design experiment course
----Do a convenient mobile keyword search library, and then realize the timely information retrieval function
----After doing a simple C language introduction tutorial, send it to CSDN - thank you for the header song support provided by boss Wang Tinghao
----After improvement: make some necessary analysis for all the functions, and make a more detailed explanation based on computer principle
----It is worth mentioning that this file is only suitable for novices who are quick to start C language to realize simple programs, and many related knowledge points such as static variables are not involved
Experiment 1
----Some of the most common basic knowledge
Basic knowledge
placeholder
- %d: Used to output signed decimal integers (including int / char types)
- %u: Used to output unsigned decimal integers (including int / char types)
- %o: Used to output unsigned octal integers
- %x: Used to output unsigned hexadecimal integers
- %c: Used to output a single character
- %s: Used to output a string
- %f: Decimal floating point number used to output decimal form (both decimal form and exponential form can be recognized when entering)
- %e: Decimal floating point number used to output exponential form (both decimal form and exponential form can be recognized when entering)
- %g: It is used to output decimal floating-point numbers that are shorter in both exponential form and decimal form (both decimal form and exponential form can be recognized when inputting)
- %. 2lf: used to output the form with two decimal places reserved
----It is widely used in input and output statements
----Bold and black are common placeholders
scanf
scanf("%d%d",&a,&b);
----Assign the obtained values to a and b respectively in order
----Note that the address fetching character & should be used to assign values
----Notice that both printf and scanf use double quotes
----If you enter, you don't need to consider whether there is space between placeholders, such as scanf_ s("%d%d", &a, &b); And scanf_ s("%d %d", &a, &b); The input method is actually the same. Enter a value and press enter, then enter a value and then press enter; That is, the interpreter will automatically distinguish between two inputs
printf
printf("a=%d,b=%d",a,b);
----When outputting, you can add necessary characters at both ends to adjust the output content without affecting the formatting
----The output parameters can directly call variables to realize the formatted replacement of the output content
----Notice that both printf and scanf use double quotes
----You need a newline character to ensure that each output is not next to each other
a++
----It means to realize the self increment of a
if
if (a==b) { printf("a and b equal\n"); printf("a and b equal\n"); }
or
if (a==b) { printf("a and b equal\n"); printf("a and b equal\n"); } else { printf("a and b Unequal\n"); printf("a and b Unequal\n"); }
or
if(i >= 'a' && i != 'q' && i<='z') { xiaoxie++; } else if(i >= 'A' && i != 'Q' && i<='Z') { daxie++; } else { qita++; }
----Note the use of if and else
Common header file
#include<stdio.h> #include<string.h> #include <stdlib.h>
----Remember to add these header files every time
Operation symbol and priority
operator | meaning | Associativity |
---|---|---|
() | brackets | |
+ - | Monocular operation, positive and negative | Right to left |
* / % | Binocular operation, multiplication and division, remainder | From left to right |
+ - | Binocular operation, addition and subtraction | From left to right |
= | Binocular operation, assignment | Right to left |
----The higher the priority, the higher the priority
Initialization of variables
double high,faHeight,moHeight,percent1=1.00,percent2=1.00;
----It can realize more concise code initialization by merging multiple lines of initialization code
----Remember to type commas and semicolons
switch
char op; double a,b,result; scanf("%lf %c %lf",&a,&op,&b); switch (op) { case '+': printf("%.2lf",(double)a+b); break; case '-': printf("%.2lf",(double)a-b); break; case '*': printf("%.2lf",(double)a*b); break; case '/': if(b==0) { printf("Divisor cannot be 0"); break; } printf("%.2lf",(double)a/(double)b); break; default: printf("Incorrect operator"); }
----Judge which part of the statement is executed by the value of the variable inside the switch bracket
----It can be noted that internally, variables and conditions are compared and judged directly through the case. When the judgment execution statement ends, you need to use break to jump out of the code block of the current case; Just type the code directly after the quotation marks
----default is used to perform additional operations without case matching. You don't need to break. You can just type the code after the quotation marks
----switch is actually a multi branch if else statement to judge whether the value of the input variable is equal to the branch content of case. It can be regarded as connecting through = = in the middle
code
0-
/* Program error correction ----Enter two integers to sum ----Change the wrong program to the correct one */ /* The following procedure is to sum a and b. The user reads in the values of a and b, calculates the results, and outputs them. There is a problem in the code and the expected effect cannot be achieved, Please correct the error directly in the following code. */ #include <stdio.h> int main() { int a,b; int sum; scanf("%d%d",&a,&b); sum=a+b; printf("sum=%d\n",sum); return 0; } /* The following program outputs "a and b are equal" when the values of a and b are equal, and there is no output if the values of a and b are not equal. There is a problem in the code and the expected effect cannot be achieved, Please correct the error directly in the following code. */ #include <stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); if (a==b) { printf("a and b equal\n"); } return 0; } /* The following procedure is that when the values of a and b are equal, the values of a and b increase by 1 at the same time, but if the values of a and b are not equal, their values remain unchanged. There is a problem in the code and the expected effect cannot be achieved, Please correct the error directly in the following code. */ #include <stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); if (a==b) { a++; b++; } printf("a=%d,b=%d",a,b); return 0; }
1-
/* The following procedure is that when the values of a and b are equal, the values of a and b increase by 1 at the same time, but if the values of a and b are not equal, their values remain unchanged. There is a problem in the code and the expected effect cannot be achieved, Please correct the error directly in the following code. */ #include <stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); if (a==b) { a++; b++; } printf("a=%d,b=%d",a,b); return 0; }
2-
/* The following procedure is that when the values of a and b are equal, the values of a and b increase by 1 at the same time, but if the values of a and b are not equal, their values remain unchanged. There is a problem in the code and the expected effect cannot be achieved, Please correct the error directly in the following code. */ #include <stdio.h> int main() { int a,b; scanf("%d%d",&a,&b); if (a==b) { a++; b++; } printf("a=%d,b=%d",a,b); return 0; }
3-
//Please write your own code completely below //Pay attention to the prompt information on the left, input and output requirements, and do not have redundant input and output #include<stdio.h> int main () { double sum; sum=1.0+1.0/2+1.0/3;//It seems that the priority of operation symbols should be emphasized here printf("%.2lf",sum);//It seems that this should emphasize the correspondence between the selection of placeholders and data types during formatting return 0; }
4-
/* Prediction of height through input data Let faHeight be his father's height, moHeight his mother's height, and the height prediction formula is Male adult height = (faHeight + moHeight) × 0.54cm Female adult height = (faHeight) × 0.923 + moHeight)/2cm Love physical exercise -- > increase height by 2% Good hygienic eating habits -- > increase height by 1.5% */ #include<stdio.h> int main() { double high,faHeight,moHeight,percent1=1.00,percent2=1.00; char sex,sport,diet; scanf("%lf %lf %c %c %c",&faHeight,&moHeight,&sex,&sport,&diet); if(sex=='M') { if(sport=='Y')percent1+=0.02; if(diet=='Y')percent2+=0.015; high=(faHeight+moHeight)*0.54;high=high*percent1+high*percent2-high; printf("%.2lf\n",high); } if(sex=='F') { if(sport=='Y')percent1+=0.02; if(diet=='Y')percent2+=0.015; high=(faHeight*0.923+moHeight)/2.0;high=high*percent1+high*percent2-high; printf("%.2lf\n",high); } return 0; }
5-
/* Calculator application ----Using switch program to design simple calculator application ----Familiar with various operators + - x/ ----Format conversion of output statement */ #include<stdio.h> #include<math.h> int main() { char op; double a,b,result; scanf("%lf %c %lf",&a,&op,&b); switch (op) { case '+': printf("%.2lf",(double)a+b); break; case '-': printf("%.2lf",(double)a-b); break; case '*': printf("%.2lf",(double)a*b); break; case '/': if(b==0) { printf("Divisor cannot be 0"); break; } printf("%.2lf",(double)a/(double)b); break; default: printf("Incorrect operator"); } return 0; }
Experiment 2
----Loop structure programming
Basic knowledge
Self operation
#include "stdio.h" int a = 1; int main(){ printf("a = %d ", a++); return a; } /*--------------------Split line--------------------*/ #include "stdio.h" int a = 1; int main() { printf("a = %d ", ++a); return a; } /*--------------------Split line--------------------*/ #include "stdio.h" int a = 1; int main() { printf("a = %d ", a+=1); return a; }
----C language self addition and self subtraction operator (+ + i / i++) Leon calls it self operation, which is convenient for overview and memory
---- printf("a = %d ", a++); The meaning of a is to output a to a first, and then + 1. Because + + is after the variable, the output is 1
---- printf("a = %d ", ++a); The meaning of is to perform the + 1 operation first, and then perform the output operation of A. because + + is in front of the variable, the output is 2
----printf("a = %d ", a+=1); The meaning of a is to perform + 1 operation first, and then perform a output operation on a, and the output is 2
----The same is true for other similar operation symbols
for loop
for(j=1;j<=i;j++) { printf("%d",j); printf("%d",j); } /*--------------------Split line--------------------*/ for(;;num++) { scanf("%d",&a); if(a<=0) { break; } sum+=a; if(a<60) { failed++; } }
----The first parameter is the initialization of variables
----The second parameter is to judge whether iteration is required, which is the starting point of each small loop
----The third parameter is used for the end of the for loop to avoid infinite loop. The operation of the third parameter will be executed only when the program in parentheses ends
----You can see that the initial parentheses of the for loop statement can be left blank as long as the code is reasonable
data conversion
avarage=(int)sum/num;
----It can be seen that forced data format conversion can be carried out in the form of (int)
ASCI code
if(i >= 'a' && i != 'q' && i<='z')
----Is the correspondence between computer characters and codes
----Single quotation marks are used to indicate the corresponding encoding of the internal string – > for example, 'A' actually corresponds to the encoding of the A character, so i > = 'A' is used to compare the value of the string corresponding to variable i on the ASCI I code. This involves the automatic conversion of A data type during operation. For the time being, it is not necessary to know about this operation method
----Here you know, characters and
code
0-
/*Analyze and modify the following program errors to make them run normally. The program is used to find the sum of integers from 1 to 100. The error code is as follows*/ void main() { int i=1,sum=0; /*Initialize loop control variable i and accumulator sum*/ while( i<=100 ) { sum += i; /*Realize accumulation*/ i++; /*Cycle control variable i increases by 1*/ } printf("sum=%d\n",sum); }
1-
/* It is required to output according to the following digital shape. There is an error in the code, please modify it correctly. 1 123 12345 1234567 The code is as follows: */ #include<stdio.h> int main() { int i,j; for(i=1;i<9;) { for(j=1;j<=i;j++) { printf("%d",j); } printf("\n"); i+=2; } }
2-
/* Student achievement entry ----Enter the scores of a group of students from the keyboard (ending with a negative number) ----Calculate the average score and count the number of failed grades. */ #include<stdio.h> #include<stdlib.h> int main() { int a,b,sum=0,num=0,avarage=0,failed=0; for(;;num++) { scanf("%d",&a); if(a<=0) { break; } sum+=a; if(a<60) { failed++; } } avarage=(int)sum/num; printf("%d %d",avarage,failed); }
4-
//Topic 3 (3) count the number of different types of characters entered by the keyboard. //Please give your schedule #include < stdio h> int main() { char i; int daxie = 0,xiaoxie = 0,qita = 0,count = 0; while(1) { scanf("%c",&i); if(i =='q') { xiaoxie++; break; } else if(i =='Q') { daxie++; break; } if(i >= 'a' && i != 'q' && i<='z') { xiaoxie++; } else if(i >= 'A' && i != 'Q' && i<='Z') { daxie++; } else if(i >= '0' && i <= '9') { count++; } else { qita++; } } printf("%d %d %d %d",count,xiaoxie,daxie,qita); return 0; }
5-
/*Topic 4 write a program and print 99 multiplication tables. Please give your program and evaluate it. Pay attention to the test set given below. To make it easier to see the code, you can delete the following content after you are familiar with the test set. 1X1=1 1X2=2 2X2=4 1X3=3 2X3=6 3X3=9 1X4=4 2X4=8 3X4=12 4X4=16 1X5=5 2X5=10 3X5=15 4X5=20 5X5=25 1X6=6 2X6=12 3X6=18 4X6=24 5X6=30 6X6=36 1X7=7 2X7=14 3X7=21 4X7=28 5X7=35 6X7=42 7X7=49 1X8=8 2X8=16 3X8=24 4X8=32 5X8=40 6X8=48 7X8=56 8X8=64 1X9=9 2X9=18 3X9=27 4X9=36 5X9=45 6X9=54 7X9=63 8X9=72 9X9=81 There is a blank space between each expression, and the multiplication sign uses the capital English letter X */#include<stdio.h> int main() { int i,j; for(i=1;i<10;i++) { for(j=1;j<10;j++) { if(j>i) { break; } printf("%dX%d=%d ",j,i,i*j); } printf("\n"); } }
6 - change converter
/* Change conversion calculator ----Change the whole money (< = 100 yuan) with a multiple of 10 yuan into a change combination of 1 yuan, 2 yuan and 5 yuan (each face value should be available). ----Input the denomination to be exchanged (e.g. 10 yuan), and output all possible exchange methods and their quantities. ----Your output is required to be combined from more to less according to the number of 5 yuan, 2 yuan and 1 yuan in turn! ----The hard calculation method is adopted here */ #include <stdio.h> int main() { int a,b,c,sum,count=0; scanf("%d",&sum); //Perform 3 consecutive iterations of for for(a=20;a>=1;a--) for(b=50;b>=1;b--) for(c=100;c>=1;c--) if(sum==a*5+b*2+c) { count++; printf("%d %d %d\n",a,b,c); } printf("%d",count); return 0; }
Experiment 3
Basic knowledge
array
One dimensional array
int num[5] scanf("%d",&a[0]) //The initialization methods are all equivalent to the following methods int a[5] = {6,2,4} int a[5] = {6,2,4,0,0} int a[ ] = {6,2,4,0,0} a[0]=6,a[1]=2,a[2]=4,a[3]=0,a[4]=0
----Define an integer data num, which contains five elements: num[0],num[1],num[2],num[3],num[4]
----Focus on the use of arrays - reference variables, which is similar to the use of variables
----Focus on initialization mode
Two dimensional array
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-g4koxslv-1640436577694) (review of header song file. assets/1640377729903.png)]
// Position by position assignment one by one int a[3][4] = {{1,2,3,4},{1,2,3,4},{1,2,3,4}} int a[3][4] = {1,2,3,4,1,2,3,4,1,2,3,4} // Assignment of some elements int a[3][4] = {{1},{1,5},{1,2,3}} ----The area where the first number is located corresponds to the first layer of parentheses---First dimension // The first dimension may be omitted and the second dimension may not be omitted int a[][4] = {1,2,3,4,5,6,7,8,9,0} int a[][4] = {{0,0,3},{},{0,10}}
Function parameters
float avgScore(float score[],int N)
Character array
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG oiomzjqe-1640436577695) (review of header song file. assets/1640377709380.png)]
----The method is exactly the same as that of an ordinary two-dimensional array
----During initialization, A[i] = '\ 0'// The end mark of the string to prevent random code -- characters and arrays must be looked at here -- let's look at it later
Character processing
//Get and output string puts(str); /* print(%os",str); */ gets(str); /* scanf("%s",str); */ //Splice string {char a[20] ="Visual"; char b[]="C++"; strcat(a ,b); printf("%s\n", a);// Visual C++ //Copy b into a or c char b[]= "C++", c[] ="Visual"; strcpy(a, c); strcat(a, b); printf("%s\n", a); //Compare the size of ASCI codes one by one from left to right //If string 1 < string 2, return a negative integer; If string 1 > string 2, return a positive integer; Returns zero if string 1 = = string 2 char str1[] ="Hell0!", str2[] ="Hello!"; if(strcmp(strl, str2)>0) printf("Hell0!> Hello!"); else if(strcmp(strl, str2)==0) printf("Hell0!= = Hello!"); else printf("Hell0!< Hello!"); //Get character length char str1[] = "Hello!"', str2[] = "How are you?"; int len1,len2,len3; len1=strlen(str1) ; len2=strlen(str2); printf(len1=%d len2=%d",len 1,len2); //Case conversion //strlwr(str) function: converts uppercase letters to lowercase letters in a string //strupr(str) function: converts lowercase letters into uppercase letters in a string //Convert string to floating point number a = atof(strA);
Bubble sorting
#include <stdio. h> / / bubble sorting optimization #define N 6 void main ( ) { int a[N], i, j, t,flag=1;//When it is 1, it indicates that there is an exchange //Enter N integers -- get data printf ("input %d numbers: \n", N); for(i=0;i<N; i++)scanf ("%d", &a[i); //sort for(i=1;i< N; i++) //N-1 bubble sort { if(flag== =0) break; //Indicates that there was no exchange in the previous - trip---- else {flag=0; //The initial is no exchange for(j=0;j<N_i; j++)//Bubble sort { if(a[j] > a[j+1]) //Exchange a[j] and a[j+1] {t= a[j]; a[j] = a[j+1]; a[j+1]= t; flag=1;} } } printf ("the sorted numbers:\n"); for(i=0;i<N; i++)printf ("%d ", a[i]);, }
code
0-
/* Correct the following program errors so that it can count the sum of array elements and output. */ #include <stdio.h> int main(void) { int sum=0; int a[5]={5,4,3,2,1}; int i; for (i=0;i<5;i++) { sum=sum+a[i]; } printf("sum=%d\n",sum); return 0; }
1-
/* Input array output processing results ----Input test set into array a ----Output the maximum and minimum values in a and find the average value (two decimal places). */ #include<stdio.h> int main() { int i,j,k,a[i]; int max,min; double avar,sum=0; scanf("%d",&i); for(j=0;j<i;j++) { scanf("%d",&k); a[j]=k; sum=sum+k; } max = a[0]; min = a[0]; for(j=0;j<i;j++) { if(a[j]>=max) { max=a[j]; } if(a[j]<=min) { min=a[j]; } } printf("%d %d ",max,min); avar=(double)sum/i; printf("%2.2lf",avar); } // The simplest sorting algorithm /* max = a[0]; min = a[0]; for(j=0;j<i;j++) { if(a[j]>=max) { max=a[j]; } if(a[j]<=min) { min=a[j]; } } */
2-
/* ----The score is divided into 10 grades of 1 ~ 10 ----1 Indicates the lowest score and 10 indicates the highest score ----Print out the histogram of statistical results in the following form --------The first column represents the score --------The second column indicates the number of scores --------The third column shows the result statistics --------Each column of data is separated by TAB character. Even if the number of scoring values is 0, there is still a TAB character after the quantity value 0 --------The last line of the test case is followed by a carriage return (\ n) INPUT 1 2 3 4 5 6 8 7 9 10 8 8 9 9 7 7 6 6 5 5 4 4 3 3 2 2 1 1 9 9 8 8 7 7 7 8 8 9 9 6 OUTPUT 1 3 *** 2 3 *** 3 3 *** 4 3 *** 5 3 *** 6 4 **** 7 6 ****** 8 7 ******* 9 7 ******* 10 1 * */ #include <stdio.h> int main() { int i,score,count; int a[10]={0}; for(i=0,count=0;i<40;i++) { scanf("%d",&score); switch(score) { case 1: a[0]++;break; case 2: a[1]++;break; case 3: a[2]++;break; case 4: a[3]++;break; case 5: a[4]++;break; case 6: a[5]++;break; case 7: a[6]++;break; case 8: a[7]++;break; case 9: a[8]++;break; case 10: a[9]++;break; } } for(i=0;i<10;i++) { printf("%d\t%d\t",i+1,a[i]); for(;a[i]>0;a[i]--) { printf("*"); } printf("\n"); } return 0; }
Experiment 4
Basic knowledge
Declarative function
long fact(long a);
----It is used to avoid that functions cannot be read normally due to the order relative relationship between functions
----The function name and parameters should be written
code
0-
/* Find the maximum of two numbers through the custom function max ----Correct mistakes */ #include<stdio.h> int max1(int a, int b) { int max; if(a>b) max=a; else max=b; return max; } int main() { int max,x,y; scanf("%d%d",&x ,&y); max=max1(x,y); printf("max=%d",max); return 0; }
1-
#include<stdio.h> long fact(long a); void main() { long n,result=0; long i,sum; scanf("%ld",&n); for(i=1;i<=n;i++) { result+=fact(i); //printf("%d\n",result) ; } printf("1!+2!+...+n!=%ld",result); } long fact(long a) { int j,sum=1; for(j=1;j<=a;j++) { sum=sum*j; } return sum; }
2-
/* Count the average score of students in a class (no more than 40 in total) */ #include <stdio.h> #include <stdlib.h> #define MAXNUM 40 void inputScore(float score[],int N); float avgScore(float score[],int N); int main() { float score[MAXNUM],avg; int N; scanf("%d",&N); /******Add the code to check the legitimacy of N. if n is not in the range of 2-40, output: input error, and exit the program******/ while(N>40||N<2) { printf("Input error"); return 0; } /*******end*************************************************************************/ inputScore(score,N); avg=avgScore(score,N); printf("The average score is%.2f",avg); return 0; } /******Please add the code defining the above two functions below according to the task requirements*******/ void inputScore(float score[],int N) { int i=0,k=0;float temp; for(;i<N;) { scanf("%f",&temp); if(temp>100||temp<0) { printf("Please re-enter\n"); continue; } score[i]=temp; //printf("%f",score[i]); i++; } } float avgScore(float score[],int N) { float sum=0,avg; int i=0; for(;i<N;i++) { sum+=score[i]; } avg=(float)sum/N; return avg; }
Experiment 5
Basic knowledge
Command line parameters
code
0-
#include<stdio.h> #include<string.h> #include <stdlib.h> /* ----Turn the executable file generated after the program is built (assuming the file name is mycal.exe) to c: \ at the command prompt ----Type Mycal 100 + 200 and the result is 300.00; Type Mycal 100 * 200, and the result is 20000.00, etc */ //s: A string in the form of a [operator] b, for example: 4.5 + 9,6-9,4 / 5,8 * 7... --- > Requirement string //After processing, the function outputs the operation result of the number. For example, if s is "20.3 + 1", the function outputs 21.30 (2 significant digits after the decimal point are reserved) - > output content on the screen //The basic algorithm of internal operation of this function is: //Step 1: find the position index corresponding to the operator //Step 2: copy the preceding string to strA and the following string to strB according to the operator position //Step 3: convert strA and strB into numerical values (use the function atof, please refer to Baidu for specific usage) a and b //Step 4: perform corresponding operations on a and b according to the operator //Step 5: output operation result /* * Function name: copy * Function: copy the numeric strings on both sides of the operator in the string s to A and B respectively */ void copy(char* s, char* A, char* B, int index) { int len = strlen(s); int i, j; for (i = 0; i < index; i++) A[i] = s[i]; A[i] = '\0'; //When assigning a value to a string, the last end should be set to \ 0 to prevent garbled code for (i = index + 1, j=0; i < len; i++, j++) B[j] = s[i]; B[i] = '\0'; } void processUserInputStr(char* s) { int len = strlen(s); //Number of valid characters in s int i; int index = -1; char strA[100] = "", strB[100] = ""; //a. B is used to store the number after string conversion, and result is used to save the operation result double a, b, result; //Stra and STRB are respectively used to store the string corresponding to two operands s[len] = '\0'; // Find the index of the operator for (i = 1; i < len; i++) //Find the operator from the second character. The operator of the first character can be a sign { if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') { index = i; break; } } //Judgment of whether operator expression format is detected if (index == -1) //No operator detected { printf("Please enter the correct expression!"); return; } copy(s, strA, strB, index); a = atof(strA); b = atof(strB); switch (s[index]) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; default: printf("Please confirm whether the expression is reasonable!"); } printf("%.2f", result); } // int main(int argc, char* argv[]) // { // //When testing the code, use the following two lines of code to comment out the third line // // char str[100] = "-123*-10\0"; // // processUserInputStr(str); // processUserInputStr(argv[1]); // return 0; // }
1-
/* ----Enter an integer (no more than 100) ----Stored in array a ----Sort and output in ascending or descending order */ // Exchanging the values of two arrays using pointers the exchange of values at two positions void swap(double* x,double* y) { double i; i=*x; *x=*y; *y=i; } /********swap End of function definition**************/ /****************Start with all other function definitions**********/ // Data entry void inputData(double* date,int N) { for(int k=0;k<N;k++) { scanf("%lf",&date[k]); } } // Array sorting void sortData(double* date,int N,int mode) { if(mode==0) { for(int i=0;i<N-1;i++) for(int j=0;j<N-1-i;j++) if(date[j]>date[j+1]) { swap(date+j,date+j+1); } } else { for(int i=0;i<N-1;i++) for(int j=0;j<N-1-i;j++) if(date[j]<date[j+1]) { swap(date+j,date+j+1); } } } // Output function void outputData(double* a,int N) { for(int i=0;i<N;i++) { printf("%.2f ",a[i]); } }
Experiment 6
Basic knowledge
structural morphology
Initialization and definition
struct student { int num ; char name[20]; char sex; int age; float score ; char addr[30]; }; struct student stu1,stu2; //------------------------Split line------------------------ struct student { int num ; char name[20]; char sex; int age; float score ; char addr[30]; }stu1,stu2;
----Note: define before naming
quote
stu.name=10; stu.score=85.5;
code
----Structure related knowledge, add it in two days
Experiment 7
Basic knowledge
File reading and writing
fopen(File name, opening method); fclose(fp); a = fgetc(fp) //Get a character fgets(str,n,fp) //Get a character with length n and save it to str fputc(ch,fp)//Write a ch string to the file fputs(str,fp)//Write the str string to the file pointer variable fp fprintf(fp,"%d %d",i,f);//Import into a file in the specified format fscanf(fp,"%d %d",&i,&f);//Gets the value from the file in the specified format
Document processing method | meaning | The specified file does not exist |
---|---|---|
"r" (read only) | To enter data, open an existing text file | report errors |
"W" (write only) | To output data, open a text file | To output data, open a text file and create a new file |
"a" (added) | Add data to the end of a text file | error |
"rb" (read only) | To enter data, open a binary file | error |
"wb" (write only) | To output data, open a binary file | Create new file |
"ab" (additional) | Add data to the end of a binary file | error |
"r +" (read / write) | To read and write, open a text file | error |
"w +" (read / write) | Create a new text file for reading and writing | Create new file |
"a +" (read / write) | To read and write, open a text file | error |
"rb +" (read / write) | To read and write, open a binary file | error |
"wb +" (read / write) | Create a new binary file for reading and writing | Create new file |
"ab +" (read / write) | Open a binary file for reading and writing | error |
code
/* ----Enter the score information of a class of students in a course, including student number, name, usual score and examination score ----The total score (= 20%) is obtained through calculation × Usual score + 80% × Test scores) and be able to store these information in text files; ----It can read all student information from the file and query the student information with the lowest and highest overall score, and display it completely. The student information is saved to a text file in the following format: 001 Zhang San 34.00 56.00 51.60 002 Li Si 68.00 90.00 85.60 */ #include<stdio.h> #include<string.h> #include<stdlib.h> #include "student.h" //Please give the complete definition of the user-defined functions used in the program below void inputInformation(Student* stus, int N) { int i; for (i = 0; i < N; i++) { printf("student%d Student number, name, usual score, examination score(Space separation):\n", i);//Output information scanf("%s%s%f%f", &stus[i].stu_number, &stus[i].stu_name, &stus[i].usual_mark, &stus[i].exam_mark);//pick up information stus[i].overall_mark = stus[i].usual_mark * 0.2 + stus[i].exam_mark * 0.8; }//Score calculation }//void does not need to return a value void saveInformation(Student* stus, int N, char* filename) { FILE* fp;//Remember the fixed operation first fp = fopen("filename", "w"); for (int i = 0; i < N; i++) { fprintf(fp, "%s %s %.2f %.2f %.2f\n", stus[i].stu_number, stus[i].stu_name, stus[i].usual_mark, stus[i].exam_mark, stus[i].overall_mark); } fclose(fp); } void outputInformation(char* filename) { printf("All students:\n"); Student min, max, * stus; stus = (Student*)malloc(sizeof(Student) * 10); int i = 0; FILE* fp; fp = fopen("filename", "r"); while (fscanf(fp, "%s %s %f %f %f", &stus[i].stu_number, &stus[i].stu_name, &stus[i].usual_mark, &stus[i].exam_mark, &stus[i].overall_mark) != EOF) { printf("Student number=%s,full name=%s,Usual performance=%.2f,Examination results=%.2f,Total Mark =%.2f\n", stus[i].stu_number, stus[i].stu_name, stus[i].usual_mark, stus[i].exam_mark, stus[i].overall_mark); i++; } fclose(fp); min = max = stus[0]; for (int j = 1; j < i; j++) { if (min.overall_mark > stus[j].overall_mark) { min = stus[j]; } if (max.overall_mark < stus[j].overall_mark) { max = stus[j]; } } printf("Lowest score student:\n"); printf("Student number=%s,full name=%s,Usual performance=%.2f,Examination results=%.2f,Total Mark =%.2f\n", min.stu_number, min.stu_name, min.usual_mark, min.exam_mark, min.overall_mark); printf("Highest score student:\n"); printf("Student number=%s,full name=%s,Usual performance=%.2f,Examination results=%.2f,Total Mark =%.2f\n", max.stu_number, max.stu_name, max.usual_mark, max.exam_mark, max.overall_mark); free(stus); }
Basic knowledge not used in the experiment but required
Constants - Definitions
#define PI 3.1415926 const double eps = 0.001; //Error accuracy
getchar & putchar
a = getchar(); putchar(a);
----The output of a is equivalent to scanf and printf, which are simplified input-output statements
do while
/*From 1 to 100*/ #include <stdio.h> int main0 int i= 1,sum=0; do { sum=sum+i; i++; } while(i<= 100]; printf("sum=%d\n" ,sum); return 0; }
----The difference from while is that while judges before execution, while do while executes before judgment
continue
void main() { int i=0; while(i<10) { if(i<1)continue; if(i==5)break; i++; } }
----It is used to jump out of this cycle of the cycle body and enter the next cycle; Corresponding to break