C language learning-function (Part 1)

6688b6b66419461c821b502734ed8c5c.png

Table of contents

Library Functions:

Custom function:

Return usage:

Array as function parameter:

Nested calls and chained access:


Library Functions:

#include <stdio.h>
#include <math.h>
int main()
{
    double d = 16.0;
    double r = sqrt(d);
    printf("%lf\n", r);
    return 0;

Custom function:

#include<stdio.h>
int Add(int x, int y)//形式上的参数,简称形参
//函数的参数就相当于,⼯⼚中送进去的原材料,函数的参数也可以是 void ,明确表⽰函数没有参数。
//如果有参数,要交代清楚参数的类型和名字,以及参数个数。
{
    int z = 0;
    int z = x + y;
    return z;
    //在这个函数中,变量z存储了变量x和y的和,并通过return 语将结果返回给调用方。returnz的作用是将z的值作为函数的结果返回。
    //调用 Add 函数时,可以通过接收返回值的变量来获取计算结果
}
//{}括起来的部分被称为函数体,函数体就是完成计算的过程。
// 
//(2)形参实际化

//(1)先写出这个函数应用场景
int main()
{
    int a = 0;
    int b = 0;
    //输入
    scanf("%d %d", &a, &b);
    //计算求和
    int z = Add(a, b);//a和b是真实传给Add的参数,是实际参数,简称实参
    //输出
    printf("%d", z);

    return 0;
}

Return usage:

  1. Return can be followed by a value or an expression . If it is an expression, the expression will be executed first and then the result of the expression will be returned . For example: 
    #include <stdio.h>
    int Add(int x,int y)
    {
        return x+y;
    }
                                                   
  2. There can also be nothing after return , just write return; this way of writing is suitable for situations where the return type of the function is void.
    #include <stdio.h>
    void test()
    {
        int n = 0;
        scanf("%d", &n);
        printf("hehe\n");
        if (n == 5)
            return ;//直接跳出返回空值void
        printf("haha\n");
    }
    
    int main()
    {
        test();
        return 0;
    }
                                                                                                                                          Note: return here is different from break. Break can only be used to break out of a loop, but subsequent operations can continue . After the return statement is executed, the function returns completely and the subsequent code is no longer executed . .code show as below:d27cad7872a94af6acac6bb3b09f4100.png
  3. If the value returned by return is inconsistent with the function return type , the system will automatically implicitly convert the returned value to the function's return type.                     Return result: 3
    int test()
    {
        return 3.14;
    }
    
    int main()
    {
        int n = test();
        printf("%d\n", n);
    
        return 0;
    }
  4.     If there is an if statement in the function, make sure there is a return in each case, otherwise a compilation error will occur.             
    #include <stdio.h>
    int test()
    {
        int n = 1;
        if (n == 5)
            return 1;
        else
            return -1;
    
    }
    
    int main()
    {
        int m = test();
        printf("%d\n", m);
        return 0;
    }

Array as function parameter:

When using functions to solve problems, arrays are passed to the function as parameters and the arrays are operated within the function.
For example: write a function to set all the contents of an integer array to -1, and then write a function to print the contents of the array .
//写⼀个函数对将⼀个整型数组的内容,全部置为-1,再写⼀个函数打印数组的内容。
#include<stdio.h>
void set_arr(int arr[], int sz)
{
  int i = 0;
  for (i = 0; i < sz; i++)
     {
      arr[i] = -1;
     }
}

void print_arr(int arr[], int sz)
{
    int i = 0;
    for (i = 0; i < sz; i++)
    {
        printf("%d", arr[i]);
    }
    printf("\n");
}
int main()
{
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int sz = sizeof(arr) / sizeof(arr[0]);//计算出数组元素个数才能遍历
    print_arr(arr, sz);//先打印出原来的元素
    //先写一个函数,将arr中的内容全部设为-1
    set_arr(arr,sz);
    //写一个函数,将arr中的内容打印出来
    print_arr(arr,sz);
    return 0;
}

The key points of passing parameters through arrays:

        

• The formal parameters of the function must match the number of actual parameters of the function
• The actual parameters of the function are arrays, and the formal parameters can also be written in array form.
• If the formal parameter is a one-dimensional array , the array size can be omitted --->arr[]
• If the formal parameter is a two-dimensional array , the rows can be omitted, but the columns cannot be omitted --->arr[][required]
• When passing parameters through arrays, formal parameters will not create a new array.
• The array of formal parameter operation and the array of actual parameters are the same array
Example of passing parameters through a two-dimensional array:
//二维数组传参
#include <stdio.h>
void print_arr(int arr[][5], int r, int c)
{
    int i = 0;
    for (i = 0; i < r; i++)
    {
        int j = 0;
        for (j = 0; j < c; j++)
        {
            printf("%d ", arr[i][j]);
        }
        printf("\n");

    }

}

int main()
{
    int arr[3][5] = { 1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7 };
    print_arr(arr, 3, 5);//数组传参
    return 0;
}

Nested calls and chained access:

Nested calls: mutual calls between functions. Each function is a Lego part. It is precisely because multiple Lego parts work seamlessly with each other that we can build exquisite Lego toys. It is also because The functions call each other effectively, and finally a relatively large program is written.

Example: Suppose we calculate how many days there are in a certain month in a certain year? , if you want function implementation, you can design 2 functions:

• is_leap_year(): Determine whether it is a leap year based on the year

• get_days_of_month(): Call is_leap_year to determine whether it is a leap year, and then calculate the number of days in this month based on the month.

 603d7f5cb4064f988db105558853b6b2.jpeg

 Leap year: A year divisible by 400.

//嵌套调用
//例子:假设我们计算某年某⽉有多少天?,如果要函数实现,可以设计2个函数:
//is_leap_year():根据年份确定是否是闰年
//get_days_of_month():调⽤is_leap_year确定是否是闰年后,再根据⽉计算这个⽉的天数
#include <stdio.h>
//(3)进一步细化判断是否为闰年
int is_leap_year(int y)
{
    if (y %400 == 0 ||( y % 100 != 0 && y %4 == 0))
        return 1;
    
    else
        return 0;
}

//(2)通过函数封装进行模块的细化--获取某年某月有多少天
int get_days_of_month(int y, int m)
{
    //巧妙利用数组进行12个月天数的输入,将月份和它对应的天数对齐
    int days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        //         0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12
    int d = days[m];//通过月份访问天数
    if(is_leap_year(y) && m==2)//判断是否为闰年并且是否为二月
    {
        d += 1;
    }
    return d;
}


//(1)根据题目含义先写出大概模块
int main()
{
    int y = 0;//年
    int m = 0;//月
    scanf("%d %d", &y, &m);//输入年月
    int d=get_days_of_month(y,m);//天数
    printf("%d", d);//打印天数
    return 0;

}

By encapsulating functions, users can call them repeatedly during use without having to rewrite the code.

summary:

• The main function calls scanf, printf, get_days_of_month
• get_days_of_month function call is_leap_year
Functions can be called nestedly, but functions cannot be nested.

 Chained access: Using the return value of one function as a parameter of another function, stringing the functions together like a chain is chained access of the function.

#include <stdio.h>
int main()
{
 int len = strlen("abcdef");//1.strlen求⼀个字符串的⻓度
 printf("%d\n", len);//2.打印⻓度 
 return 0;
}
#include <stdio.h>
int main()
{
 printf("%d\n", strlen("abcdef"));//链式访问
 return 0;
}
Use the return value of strlen directly as the parameter of the printf function, which is a chained access.
✨Look at an interesting code. What is the result of executing the following code?
#include <stdio.h>
int main()
{
   printf("%d", printf("%d", printf("%d", 43)));
   return 0;
}

-------------------------->The operation result is 4321, why is this?

-------------------------->The key to this code is to understand what the printf function returns? 8ab64b8f70bf4f24a98fb94fe6fc4801.png

According to the return value of the printf function on the C language official website, it can be seen that it returns the number of characters printed on the screen.

In the above example, the first printf prints the return value of the second printf, and the second printf prints the third
The return value of printf.
The third printf prints 43, prints 2 characters on the screen, and returns 2
The second printf prints 2, prints 1 character on the screen, and then puts 1 back
The first printf prints 1
So the final print on the screen is: 4321

Guess you like

Origin blog.csdn.net/Aileenvov/article/details/132483629