[Z1-up] 1 The first C + + program

1, Main framework of program

Example

Please enter the following program and press "run" to see what will happen?

# include <iostream>
using namespace std;
 
int main ()
{
  cout << "Hello world!"; //This line controls the output Hello World !
  return 0;
}

This is a very classic program. Let's understand each part and its role one by one.

(1) The "#include < iostream >" section is called the header file.

The header file can be understood as a toolkit. When we need to use specific tools, we need to tell the computer in advance that we need to call the corresponding toolkit.

iostream, i is the abbreviation of in, indicating input; o is short for out, indicating output; Stream means stream; Therefore, this header file represents an input / output stream, and the tools we use most are cin and cout.

(2)using namespace std; This part is called the namespace.

Because there are many name spaces inside the program, some words may be repeated. If they are not explained, the calculator will not know which name space we are talking about, and then an error will be reported.

Try to delete this sentence and see what happens?

The program will report an error and prompt that cout is wrong. You can add std:: in front of cout to achieve the same purpose.

However, it is not convenient to add this prefix to each special noun at this time, so it is recommended to write using namespace std directly at the beginning; this sentence.

(3) int main() {} This part is called the main function and is the main body of the whole program.

The first word int represents the data type of the returned result of the program. We don't need to go into this for the time being. The main function is generally int, and it is usually followed by a return 0 inside the program; Match as a fixed match.

Error prone point: the main word is misspelled and the brackets are forgotten.

Inside the braces are the code statements of the program, that is, the instructions executed by the computer.

Different statements use semicolon segmentation. Don't forget to use semicolon!

cout << " Hello world !"; It means that the computer should output "Hello world!" this sentence.

(4) Later / / this line controls the output of Hello World! It's a note. This part is not read by the computer, but for people. The purpose is to facilitate yourself or others to understand the meaning of the code, especially in some complex code, appropriate code is very necessary.

What if the code is very long and needs to wrap?

At this point, you can use the combination of / * * / to write code.

#include <iostream>
using namespace std;

int main ()
{
    cout << " Hello world !"; /*This line controls the output Hello World!
    This line is just a simple comment,
    So is this business*/
    return 0;
}

 

[example] error checking: code module

 

[analysis]

A "#" is missing in the header file; The file name is misspelled. It should be iostream.

Namespace is misspelled. It should be namespace; There is no semicolon after std.

The name of the main function is misspelled. It is main, followed by a pair of parentheses.

The curly braces of the main function body are not paired, and a curly brace should be added at the end.

h and w should be capitalized in the output string, and there is no space after the exclamation point; The newline character is endl;

Semicolons use Chinese semicolons. Switch to English semicolons.

return 0 is not followed by a semicolon.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

 

2, cout statement

The general format of cout statement is:

Cout < < project 1 < < project 2 < <... < project n;

(1) String output

If the item is enclosed in double quotation marks, the program will output the contents inside the double number.

[try] if the output statement is cout < < Hello < < world; What is the output?

If you want the output statement to wrap, you need to use endl.

Cout < < project 1 < < endl;

Cout < < project 2 < < endl;

Banana Song

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << "ba ba ba ba ba na na" << endl;
    cout << "ba ba ba ba ba na na" << endl;
    cout << "bananaaaaaaah!" << endl;
    return 0;
}

Of course, only one cout can achieve this goal, as shown below.

#include <iostream>
using namespace std;

int main()
{
    cout << "ba ba ba ba ba na na" << endl  << "ba ba ba ba ba na na" << endl << "bananaaaaaaah!" << endl;
    return 0;
}

But in terms of reading aesthetics, generally choose the one above, because it will be more in line with human reading habits.

 

[practice] character love

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << " ** ** " <<endl;
    cout << "*******" <<endl;
    cout << "*******" <<endl;
    cout << " *****" <<endl;
    cout << "  ***" <<endl;
    cout << "   *" <<endl;
    return 0;
}

 

(2) Expression output

If the project itself is an expression, cout will directly output the evaluation result of the expression.

There are five basic arithmetic symbols in C + + Language: add (+), subtract (-), multiply (*), divide (/), module (%).

The first four are basically consistent with the arithmetic symbols of mathematics. The fifth is actually the remainder. For example, 14 ÷ 5 = 2... 4, then 14% 5 = 4.

Example

Run the following programs to realize the relationship and difference between programming arithmetic operators and mathematical operators.

#include <iostream>
using namespace std;

int main ()
{
    cout << 7 + 2 << endl;
    cout << 7 - 2 << endl;
    cout << 7 * 2 << endl;
    cout << 7 / 2 << endl;
    cout << 7 % 2 << endl;
    return 0;
}

Note that the result of the fourth operator is not 3.5 as we expected, but 3.

The reason is that if both the divisor and the divisor are integers, then "/" is actually a quotient symbol.

So what if you want to output the actual decimal results?

At this time, as long as the divisor or divisor is written in the form of decimal, such as 7.0/2 or 7 / 2.0, the result is normal 3.5.

 

The operation order of these operators is the same as that in Mathematics: multiply and divide modules first, then add and subtract, and calculate the in parentheses first.

Arithmetic expression

 

[analysis]

take × Replace with *, and replace ÷ with /. Note that there are no square brackets in the programming language. They are all small brackets.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << 123 * 3145 - 2015 / 5 << endl;
    cout << 1.23 * 4.34 / 2.5 - 0.1234 << endl;
    cout << (2348 * (1345 + 114) - 116) / 8 << endl;
    cout << 123456789 % 123 << endl;
    return 0;
}

 

Numerical operation

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << 123321 * 456 + 5678910 << endl;
    cout << 245645345 / 1233 << endl;
    cout << 245645345 % 1233 << endl;
    cout << 11 * 12 + 12 * 13 + 13 * 14 + 14 * 15 + 15 * 16 << endl;
    cout << 1.23 * 5.67 << endl;
    return 0;
}

 

[example] unit conversion

[analysis]

8000÷60=130......200,130÷60=2......10.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << 8000 / 3600 << ' ' << 8000 / 60 % 60 << ' ' << 8000 % 60 << endl;
    return 0;
}

 

Floor tile laying

[analysis]

Note that the result of 90 ÷ 4 ÷ 3 is decimal, and 90 needs to be written as 90.0.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << 90.0 / 4 / 3 * 5 * 6;
    return 0;
}

 

3, Variables and assignments

If a quantity has different values or changes, we need a "container" to store the changed quantity, which is called a variable.

The storage space used by different data is different, and the size of the "container" to be used is also different. Therefore, before using a variable, you need to define the data type of the variable.

 

Boolean actually means true and false. 0 is false and 1 is true. We'll talk about it in detail when we learn the branch structure later.

Character type is used to represent letters and symbols.

In the data calculation stage, we often use the latter. In the initial stage, it can be understood according to the following rules for the time being:

If it's an integer, use int. if it's a large integer, use long long.

If it is a decimal, float is used for low precision and double is used for high precision, but double is generally used directly.

 

Variable naming rules:

(1) Only letters (a ~ Z, a ~ z), numbers (0 ~ 9) and underscores () can appear in variable names, Counter example: UsD$

(2) The first character cannot be a number. Counterexample: 2PAC

(3) Cannot be a C + + keyword, counterexample: int.

(4) Case sensitive, a and a are two different variables.

 

The process of assigning a variable to a specific value is called assignment.

Example

Observe the following assignment procedures to understand the relationship between variables and assignment.

#include <iostream>
using namespace std;

int main ()
{
    int a;
    a = 10;
    cout << a << endl;
    a = 20;
    cout << a << endl;
    int b = 30;
    a = b;
    cout << a << endl;
    int c = 40;
    c = a;
    cout << a << endl;
    return 0;
}

If the right is also a variable, the value of this variable will be passed to the left. Different from the "=" in mathematics, the "=" in the program indicates assignment, that is, the value on the right of "=" is assigned to the variable on the left.

The assignment process has a strong characteristic of "liking the new and hating the old", that is, the new value will directly replace the original value.

 

Any variable needs to be declared in advance to tell the computer the type and size of the variable.

The declaration and assignment of variables can be carried out at the same time, but only the assignment of one variable. If the assignment of even equation occurs, it cannot be carried out at the same time with the declaration. For example, the following situation is not feasible.

int a=b=c=0;

If the variable assignment process is based on itself, it can be simplified.

For example, a=a+2 can be abbreviated as a+=2, and a-=2 means a=a-2.

Example

Observe the following assignment procedures to understand the characteristics of variable re assignment on its own basis.

#include <iostream>
using namespace std;

int main ()
{
    int a = 10;
    a += 1;
    cout << a << endl;
    a -= 2;
    cout << a << endl;
    a *= 3;
    cout << a << endl;
    a /= 4;
    cout << a << endl;
    a %= 5;
    cout << a << endl;
    a++;
    cout << a << endl;
    a--;
    cout << a << endl;
    return 0;
}

It should be noted that in the last two, a + + is the abbreviation of a+=1, that is, a increases by 1; And a -- is a minus one.

There is another way to write self increase and self decrease: + a and -- b. the difference between them and the previous two lies in the order of assignment and calculation.

Example

Observe the following procedures to understand the sequence of assignment and calculation.

#include <iostream>
using namespace std;

int main ()
{
    int a, b;
    a = 10;
    b = a++;
    cout << b << endl;
    b = ++a;
    cout << b << endl;
    b = a--;
    cout << b << endl;
    b = --a;
    cout << b << endl;
    return 0;
}

 

[practice] error checking: variable definition

[analysis]

$a variable definition is illegal and special symbols cannot appear;

1b illegal variable definition, the first character of the variable cannot be a number;

The definitions of C0, CO and co variables are not uniform. They should be case sensitive and pay attention to the difference between 0 and o;

___ Variable definitions are not unified. The second one has only two characters and should be unified as _;

int keyword cannot be defined as a variable;

sum variable is not defined;

2=1b the assignment process is wrong, and the variable should be written on the left.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    int a, b, C, ___, in;
    a = 1;
    b = 2;
    C = 3;
    ___ = 4;
    in = 0;
     int sum = a + b + C + ___ + in;
    cout << sum <<endl;
    return 0;
}

 

If a quantity needs to be called repeatedly in the program and the value needs to be kept constant, a constant can be defined.

The definition format of constants is as follows:

int const a=2, or const int a=2.

 

4, cmath header file and common functions

1. Accuracy and estimation

The calculation results need to be approximated. There are three common functions:

(1) floor(a), round down the floating point number a

(2) ceil(a), round up the floating point number a

(3) round(a) to round the floating point number a

[thinking] what should I do if I want to round the result to one decimal place?

Answer: multiply by 10, then round, and then divide the result by 10.

Rounding

 

[reference code]

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double a = 314.15926;
    cout << ceil(a) << endl;
    cout << floor(a) << endl;
    cout << round(a) << endl;
    cout << round(a * 100) / 100 << endl;
    return 0;
}

 

2. Power and square root

The Y power of X, that is, xy, is expressed as pow(x,y) in C + + language. For example, the third power of a can be expressed as pow(a,3).

If you want to square x, that is, expressed as sqrt(x) in C + +.

 

Power and formula

 

[reference code]

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    cout << pow(2, 16) << endl;
    cout << sqrt(1522756) << endl;
    return 0;
}

 

Formula conversion

 

[analysis]

2x should be written as 2*x

[reference code]

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double a, x, y;
    x = 1.2;
    y = 1.3;
    a = (2*x+pow(y,3))/(pow(x,2)+3*y);
    cout << a << endl;
    return 0;
}

 

5, After class practice

[1] Output "Hello World!"

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    cout << "Hello World!" << endl;
    cout << "Hello World!" << endl;
    return 0;
}

 

[2] Triangular area

[analysis]

twenty-three × 51 ÷ 2, the result is decimal. Note that the data is written in decimal form.

[reference code]

#include <iostream>
using namespace std;

int main()
{
    cout << 23.0 * 51 / 2;
    return 0;
}

 

Added by paschim on Wed, 12 Jan 2022 11:59:06 +0200