sqrt function in C language

Table of contents:

                Foreword:

statement:

Build environment:

Column:

Parameters and return value of sqrt function:

Simple practice:

question:

discuss:

Improve:


Foreword:

In daily life, we often need to use computers to perform huge operations, such as finding the square root of a number. In this chapter I will teach you how to write a program called "find the square root of a number". But it was a little difficult to write this program before we learned the sqrt function in C language. But after learning the sqrt function, we will greatly reduce the difficulty of writing, so when we write the program "finding the square root of a number", we must We need to learn the sqrt function, but before learning the sqrt function, we must set up an environment to use the sqrt function. Why do we need to learn the sqrt function to do this program? Because the sqrt function just finds the square root of a number.

statement:

The author of this article is a first-year junior high school student. The square root was learned by the author through preview, so the article may have some errors. If there are any errors, I hope readers who pass by can correct them in the comment area.

Build environment:

There is no doubt that when we use a function in C language, we must include the header file of this function (I believe that readers with a certain foundation in C language will know). The header file of the sqrt function is <math.h> (mathematical header file), so we first need to use the "#include" macro to include a <math.h> header file, as shown in the following figure:

#include<math.h>

Even if we include the header file of the sqrt function, we not only need the results calculated by the sqrt function, but also need a function that can output the calculation results. This function is the printf function, and the printf function is print format (formatted output) Abbreviation, the header file it contains is <stdio.h> (standard input and output), we also need to include this header file for input and output.

#include<math.h>
#include<stdio.h>

Then we need to build a function named "main". Why do we need to build this function? Because this is the entry function of the entire C program, almost all statements will be executed in the main function (for detailed methods of building the main function, please see the author's "putchar function in C language". Although this blog focuses on the putchar function , but it also explains in detail how to build the main function. Readers in need please jump to this link:  putchar function in C language  . Even if the reader does not read the explanation of the main function in the linked blog, we will still explain the main function in this blog. functions are explained).

#include<math.h>
#include<stdio.h>

int main(void)
{


    return 0;
}

(The following column is an explanation of the main function, experienced readers can skip it)

Column:

                                                        Interpret the main function

The data type of the main function we created is int type and has no parameters. You can fill in "void" or not in the parameter list of the main function. Followed by "{}", the content wrapped by "{}" is called the function body, and the function body can contain statements that need to be executed. "retrun 0;" in the function body is optional on most compilers. That is to say, writing "retrun 0;" in the main function is completely equivalent to not writing "retrun 0;", but in order to avoid The meaning of the language is unclear (referred to as ambiguity). The author hereby recommends that you add the statement "return 0;" at the end of the main function.

After setting up the environment, we can officially start learning the sqrt function.

Parameters and return value of sqrt function:

To use a function correctly, you must pass parameters correctly. To pass parameters correctly, you need to know the data type of the parameter and the number of parameters required by the function. In the VS compiler (referred to as: Microsoft Visual Stduio), we only need to move the mouse cursor over the function to easily know the parameters required by the function and the number of parameters, but we must create a Only projects will do (since it is relatively simple to create a project in the VS compiler, the author will not elaborate here).

We place the mouse cursor on the sqrt function and it is not difficult to find that the parameter of the sqrt function is a variable of double type (double precision floating point), and the type of the return value is also of type double (note: we need time when passing parameters Pay attention to the data type of the parameter). After we have a brief understanding of the parameters and return values ​​of the sqrt function, we can start the next step.

Simple practice:

Here we have already started to make a program to "find the square root of a number". Let's first try to pass a parameter to the sqrt function and output it to see if the actual result is consistent with our ideal result. For example, if we want to query the calculation result of square root 4, we can do this:

#include<math.h>
#include<stdio.h>

int main(void)
{
    printf("%lf",sqrt(4));

    return 0;
}

We know that the result of square root 4 is 2, and the output result should also be 2. Let's see if the actual output result is consistent with our ideal output result.

Output result: 2.000000

The answer is indeed correct, but I don’t know why the output result has so many 0s after the decimal point? This doesn't really matter, what we care about is the correctness of the output. The above code is a bit difficult to understand, but it doesn’t matter! We will discuss this together below. However, readers will inevitably have doubts about the examples before discussing, so it is necessary for us to answer beginners’ questions before starting the discussion:

question:

Q1: "Isn't the type of the sqrt function parameter a double-precision floating point type? Why in the above example is the parameter of the sqrt function an integer, isn't it a floating point number? Will there be any problems in passing parameters like this? "

R1: It is necessary to answer the reader who asked this question here: "It is completely correct to pass a floating point number to the sqrt function, and there is nothing wrong at all. Of course, there is no problem in passing an integer to the sqrt function, because passing an integer to the sqrt function Integer variables will be automatically converted to double-precision floating-point types. So can we avoid the process of converting parameters from integer types to double-precision floating-point types? Of course. But we need to make a small modification to the code above :

#include<math.h>
#include<stdio.h>

int main(void)
{
    printf("%lf",sqrt(4.0));

    return 0;
}

This change can avoid the process of converting parameters from integer to floating point, and the code will become more accurate.

Q2: "The first parameter in the printf function is the strange string ("%lf"). Why is the strange string not output? It is replaced by a number."

R2: This is a very good question! If you simply think that this is just a strange string, it seems right, because if it is your first contact, you will inevitably feel strange, which is very normal. But "%lf" is not a strange string, but a placeholder , which is almost indispensable when we write C programs every day. You can understand it this way: "printf means 'formatted output'. You can understand this placeholder as the formatting in "formatted output". It can output the subsequent parameters according to the content of the placeholder, for example Under the same printf function, the first placeholder outputs the content of the second parameter, the second placeholder outputs the content of the third parameter, and so on. The way to distinguish whether it is a placeholder is also very simple. Look at whether "%" (percent sign) appears in front of a string. If there is, it means that it is a placeholder. If not, it means that it is not a placeholder. . In C language, there are not only "%lf" placeholders, but also many placeholders. The following table is the commonly used placeholders in C language. The input and output format corresponding to each placeholder is different.

%d Input and output in the form of integers
%f Input and output in the form of single-precision floating point types
%lf Input and output as double precision floating point types
%s

Input and output in the form of strings

(If you are confused about the examples above, please tell the author in the comment area, and the author will respond to you in time and update your questions for this article)

discuss:

In order to make readers better understand, we can make a rough translation of the code of the above example (here the author "moved" the code of the above example to the following, the reason for doing this is to prevent readers from looking back at the above).

#include<math.h>
#include<stdio.h>

int main(void)
{
    printf("%lf",sqrt(4.0));

    return 0;
}

Translation: First include two header files in the program, they are: math.h (mathematical header file) and stdio.h (standard input and output header file). Then we need to write the main function. The data type of the "main" function is int, and the data type of the parameter is "void". Why write the "main" function? Because it is the entrance to the entire C program, there are two statements in the function body of the main function. The first one is "printf("%lf",sqrt(4.0));", which translated means: "With double Output the return value of the sqrt function in the form of precision floating point (note: when a function is used as a parameter of another function, the program will first calculate the return value of one function and then pass it to the parameter of the other function). "The last statement is "return 0;". The function must need a return value, except for the void type. The data type of our main function is int, not void, so the main function needs a return value, although in Most compilers omit the return value of the main function, but even so, it is best to add the return value. This is a good habit! .
(Note: Do not regard void in the parameter list of the main function as the data type of the main function)

Improve:

In fact, it is not difficult for us to find that there are many problems with this program. For example, I don’t want to ask for the square root of 4 anymore. I want to try to find the square root of 2. But how do I change the parameters of the sqrt function? Wouldn't it be better if I made changes to "4" directly from the program's source code? However, every time you find the square root of a number, you must make changes to the source code of the program, which will lead to a significant reduction in efficiency, so in the long run, this is not a good solution. So since we don't start with the source code of the program, why don't we start with the console? Because our input and output are almost always done on the console. So we can write the square root number we require into a variable, and finally send it to the sqrt function and use the printf function to output it. Obviously this is a good way to avoid changes to the source code of the program and improve improve the stability of the source code. This is obviously a good solution. good! Just do it!

The object to be written is a variable, so before that we need to create a variable to become the object to be written. The data type of the variable needs to be double type. Why is it double type? Because the parameter type required by the sqrt function is Double, and we need to send this variable to the sqrt function and use the printf function to output, the output format is in the form of double-precision floating point, so this variable is double-precision Floating point type (Double) is well deserved. The name of the variable we created is called "sum", and the initial value of "sum" is 0. As shown in the following code block:

#include<math.h>
#include<stdio.h>

int main(void)
{
    double sum = 0;

    printf("%lf",sqrt(4.0));

    return 0;
}

The writing function we use is the scanf (formatted input) function, which requires us to input data based on the content of the placeholder. It is the opposite of the printf function, which outputs data based on the content of the placeholder. Still the old saying: "If you want to use the function correctly, you must pass the parameters correctly. If you want to pass the parameters correctly, you need to know the data type of the parameter and the number of parameters required by the function." So let's take a look at the parameters of the scanf function. prototype:

 At first glance, we don’t seem to understand the parameter requirements of the scanf function, because half of the parameters are omitted, but we generally know that the parameters required by the scanf function are a placeholder and a variable that needs to be written. Like this:

scanf("占位符",&被写入数据的变量);

(Some readers may ask what does this "&" mean? We won't care about this for now, we will talk about it below)

This "variable to which data is written" is exactly our "sum" variable. Writing data to the "sum" variable can be expressed as follows:

scanf("%lf",&sum);

So what does this "&" mean? "&" is the address character in C language. Because we want to write data in the address unit where the variable is located, we need to get the address unit where the variable is located. Just add the address before the variable of the second parameter. The scanf function can be used only if required.

#include<math.h>
#include<stdio.h>

int main(void)
{
    double sum = 0;

    scanf("%lf",&sum);

    printf("%lf",sqrt(4.0));

    return 0;
}

In this way, as long as we enter the value of the variable we want on the console, and press Enter, the value of the variable will be what we wrote on the console. But one thing to note is that each data type has its own value range, so the input data cannot be larger or smaller than the value range of the input variable, otherwise overflow or underflow will occur.

The parameters of the sqrt function are exactly the variables we use to input data, so we directly feed the variable "sum" into the sqrt function to calculate the square root number we want.

#include<math.h>
#include<stdio.h>

int main(void)
{
    double sum = 0;

    scanf("%lf",&sum);

    printf("%lf",sqrt(sum));

    return 0;
}

In this way, our "find the square root of a number" program is complete, and it has extremely high efficiency. We can test the above code first. Suppose we want to find the square root of 2, we need to enter 2 on the program's console and press Enter. The value of the "sum" variable is assigned to 2, and then the value of "sum" is sent to the sqrt function, and the result of the sqrt function is returned to the printf function and output.

Input data: 2

Output result: 1.414214

Although this result is not accurate for scientific researchers, it is accurate enough for ordinary people like us. It's clear this program is a success.

In addition, we can also prompt the user to enter a piece of information for the next statement before the scanf function, and we can also modify the output result.

#include<math.h>
#include<stdio.h>

int main(void)
{
    double sum = 0;

    printf("请输入一个数值,我们会帮助您计算出这个数的平方根");
    scanf("%lf",&sum);

    printf("这个数的平方根是:%lf",sqrt(sum));

    return 0;
}

This completes the entire "finding the square root of a number" procedure.

Guess you like

Origin blog.csdn.net/m0_68824353/article/details/126568702