C++ Study Notes (6)

C++ loop

Sometimes, it may be necessary to execute the same block of code multiple times. In general, statements are executed sequentially: the first statement in a function is executed first, followed by the second statement, and so on.

Programming languages ​​provide various control structures that allow more complex execution paths.

A loop statement allows us to execute a statement or group of statements multiple times, the following is the general form of a loop statement in most programming languages:

cycle type

The C++ programming language provides the following types of loops. Click on the links to see details of each type.

cycle type

describe

while loop

Repeats a statement or group of statements while the given condition is true. It tests the condition before executing the loop body.

for loop

Executes a sequence of statements multiple times, simplifying code that manages loop variables.

do...while loop

Similar to a while statement, except that it tests the condition at the end of the loop body.

nested loop

You can use one or more loops inside a while, for, or do..while loop.

loop control statement

Loop control statements alter the normal sequence of execution. When execution leaves a scope, all automatic objects created in that scope are destroyed.

C++ provides the following control statements. Click on the links to view the details of each statement.

control statement

describe

break statement

termination

loop

or

switch

statement, program flow continues with the next statement immediately following the loop or switch.

continue statement

Causes the loop to skip the remainder of the body, immediately restarting testing the condition.

goto statement

Transfer control to the marked statement. But it is not recommended to use the goto statement in the program.

Infinite loop

If the condition never becomes false, the loop becomes an infinite loop. A for loop can be used in the traditional sense to implement an infinite loop. Since none of the three expressions are required to form a loop, you can leave some conditional expressions blank to form an infinite loop.

example

#include iostream>

using namespace std;

int main ()

{

for( ; ; )

{

printf("This loop will run forever.\n");

}

return 0;

}

When the conditional expression is absent, it is assumed to be true. You can also set an initial value and increment expressions, but in general, C++ programmers prefer to use the for(;;) construct to represent an infinite loop.

NOTE: You can press Ctrl + C to terminate an infinite loop.

C++ judgment

Predicate constructs require the programmer to specify one or more conditions to be evaluated or tested, along with statements to execute if the conditions are true (required) and statements to execute if the conditions are false (optional).

Here is the general form of a typical predicate construct in most programming languages:

Judge sentences

The C++ programming language provides the following types of judgment statements. Click on the links to view the details of each statement.

statement

describe

if statement

one

if statement

Consists of a Boolean expression followed by one or more statements.

if...else statement

one

if statement

may be followed by an optional

else statement

, the else statement is executed if the Boolean expression is false.

Nested if statements

You can use a

if

or

else if

statement using another

if

or

else if

statement.

switch statement

one

switch

statement allows testing when a variable is equal to more than one value.

Nested switch statements

You can use a

switch

statement using another

switch 

statement.

? : operator

We have explained  the conditional operator ? : in the previous chapter , which can be used instead of the if...else statement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

where Exp1, Exp2, and Exp3 are expressions. Note the use and placement of colons.

? The value of the expression is determined by Exp1. If Exp1 is true, the value of Exp2 is evaluated and the result is the value of the entire ? expression. If Exp1 is false, the value of Exp3 is evaluated and the result is the value of the entire ? expression.

C++ function

A function is a group of statements that together perform a task. Every C++ program has at least one function, the main function main() , and all simple programs can define other additional functions.

You can divide the code into different functions. How you divide your code into different functions is up to you, but logically, the division is usually done in terms of each function performing a specific task.

A function declaration tells the compiler the function's name, return type, and parameters. A function definition provides the actual body of the function.

The C++ standard library provides a large number of built-in functions that programs can call. For example, the function strcat() is used to concatenate two strings, and the function memcpy() is used to copy memory to another location.

There are many other names for functions, such as methods, subroutines, or programs, and so on.

define function

The general form of a function definition in C++ is as follows:

return_type function_name( parameter list )

{

body of the function

}

In C++, a function consists of a function header and a function body. Here is a list of all the components of a function:

  • 返回类型:一个函数可以返回一个值。return_type 是函数返回的值的数据类型。有些函数执行所需的操作而不返回值,在这种情况下,return_type 是关键字 void。
  • 函数名称:这是函数的实际名称。函数名和参数列表一起构成了函数签名。
  • 参数:参数就像是占位符。当函数被调用时,您向参数传递一个值,这个值被称为实际参数。参数列表包括函数参数的类型、顺序、数量。参数是可选的,也就是说,函数可能不包含参数。
  • 函数主体:函数主体包含一组定义函数执行任务的语句。

实例

以下是 max() 函数的源代码。该函数有两个参数 num1 和 num2,会返回这两个数中较大的那个数:

// 函数返回两个数中较大的那个数

int max(int num1, int num2)

{

// 局部变量声明

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

函数声明

函数声明会告诉编译器函数名称及如何调用函数。函数的实际主体可以单独定义。

函数声明包括以下几个部分:

return_type function_name( parameter list );

针对上面定义的函数 max(),以下是函数声明:

int max(int num1, int num2);

在函数声明中,参数的名称并不重要,只有参数的类型是必需的,因此下面也是有效的声明:

int max(int, int);

当您在一个源文件中定义函数且在另一个文件中调用函数时,函数声明是必需的。在这种情况下,您应该在调用函数的文件顶部声明函数。

调用函数

创建 C++ 函数时,会定义函数做什么,然后通过调用函数来完成已定义的任务。

当程序调用函数时,程序控制权会转移给被调用的函数。被调用的函数执行已定义的任务,当函数的返回语句被执行时,或到达函数的结束括号时,会把程序控制权交还给主程序。

调用函数时,传递所需参数,如果函数返回一个值,则可以存储返回值。例如:

实例

#include iostream>

using namespace std;

// 函数声明

int max(int num1, int num2);

int main ()

{

// 局部变量声明

int a = 100;

int b = 200;

int ret;

// 调用函数来获取最大值

ret = max(a, b);

cout "Max value is : " ret endl;

return 0;

}

// 函数返回两个数中较大的那个数

int max(int num1, int num2)

{

// 局部变量声明

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

把 max() 函数和 main() 函数放一块,编译源代码。当运行最后的可执行文件时,会产生下列结果:

Max value is : 200

函数参数

如果函数要使用参数,则必须声明接受参数值的变量。这些变量称为函数的形式参数。

形式参数就像函数内的其他局部变量,在进入函数时被创建,退出函数时被销毁。

当调用函数时,有三种向函数传递参数的方式:

调用类型

描述

传值调用

该方法把参数的实际值赋值给函数的形式参数。在这种情况下,修改函数内的形式参数对实际参数没有影响。

指针调用

该方法把参数的地址赋值给形式参数。在函数内,该地址用于访问调用中要用到的实际参数。这意味着,修改形式参数会影响实际参数。

引用调用

该方法把参数的引用赋值给形式参数。在函数内,该引用用于访问调用中要用到的实际参数。这意味着,修改形式参数会影响实际参数。

默认情况下,C++ 使用传值调用来传递参数。一般来说,这意味着函数内的代码不能改变用于调用函数的参数。之前提到的实例,调用 max() 函数时,使用了相同的方法。

参数的默认值

当您定义一个函数,您可以为参数列表中后边的每一个参数指定默认值。当调用函数时,如果实际参数的值留空,则使用这个默认值。

这是通过在函数定义中使用赋值运算符来为参数赋值的。调用函数时,如果未传递参数的值,则会使用默认值,如果指定了值,则会忽略默认值,使用传递的值。请看下面的实例:

实例

#include iostream>

using namespace std;

int sum(int a, int b=20)

{

int result;

result = a + b;

return (result);

}

int main ()

{

// 局部变量声明

int a = 100;

int b = 200;

int result;

// 调用函数来添加值

result = sum(a, b);

cout "Total value is :" result endl;

// 再次调用函数

result = sum(a);

cout "Total value is :" result endl;

return 0;

}

当上面的代码被编译和执行时,它会产生下列结果:

Total value is :300 Total value is :120


Lambda 函数与表达式

C++11 提供了对匿名函数的支持,称为 Lambda 函数(也叫 Lambda 表达式)。

Lambda 表达式把函数看作对象。Lambda 表达式可以像对象一样使用,比如可以将它们赋给变量和作为参数传递,还可以像函数一样对其求值。

Lambda 表达式本质上与函数声明非常类似。Lambda 表达式具体形式如下:

[capture](parameters)->return-type{body}

例如:

[](int x, int y){ return x < y ; }

如果没有返回值可以表示为:

[capture](parameters){body}

例如:

[]{ ++global_x; }

在一个更为复杂的例子中,返回类型可以被明确的指定如下:

[](int x, int y) -> int { int z = x + y; return z + x; }

本例中,一个临时的参数 z 被创建用来存储中间结果。如同一般的函数,z 的值不会保留到下一次该不具名函数再次被调用时。

如果 lambda 函数没有传回值(例如 void),其返回类型可被完全忽略。

在Lambda表达式内可以访问当前作用域的变量,这是Lambda表达式的闭包(Closure)行为。 与JavaScript闭包不同,C++变量传递有传值和传引用的区别。可以通过前面的[]来指定:

[] // 沒有定义任何变量。使用未定义变量会引发错误。 [x, &y] // x以传值方式传入(默认),y以引用方式传入。 [&] // 任何被使用到的外部变量都隐式地以引用方式加以引用。 [=] // 任何被使用到的外部变量都隐式地以传值方式加以引用。 [&, x] // x显式地以传值方式加以引用。其余变量以引用方式加以引用。 [=, &z] // z显式地以引用方式加以引用。其余变量以传值方式加以引用。

另外有一点需要注意。对于[=]或[&]的形式,lambda 表达式可以直接使用 this 指针。但是,对于[]的形式,如果要使用 this 指针,必须显式传入:

[this]() { this->someFunc(); }();

C++ 数字

通常,当我们需要用到数字时,我们会使用原始的数据类型,如 int、short、long、float 和 double 等等。这些用于数字的数据类型,其可能的值和数值范围,我们已经在 C++ 数据类型一章中讨论过。

C++ 定义数字

我们已经在之前章节的各种实例中定义过数字。下面是一个 C++ 中定义各种类型数字的综合实例:

实例

#include iostream>

using namespace std;

int main ()

{

// 数字定义

short s;

int i;

long l;

float f;

double d;

// 数字赋值

s = 10;

i = 1000;

l = 1000000;

f = 230.47;

d = 30949.374;

// 数字输出

cout "short s :" s endl;

cout "int i :" i endl;

cout "long l :" l endl;

cout "float f :" f endl;

cout "double d :" d endl;

return 0;

}

当上面的代码被编译和执行时,它会产生下列结果:

short s :10 int i :1000 long l :1000000 float f :230.47 double d :30949.4

C++ 数学运算

在 C++ 中,除了可以创建各种函数,还包含了各种有用的函数供您使用。这些函数写在标准 C 和 C++ 库中,叫做内置函数。您可以在程序中引用这些函数。

C++ 内置了丰富的数学函数,可对各种数字进行运算。下表列出了 C++ 中一些有用的内置的数学函数。

为了利用这些函数,您需要引用数学头文件 。

序号

函数 & 描述

1

double cos(double);

该函数返回弧度角(double 型)的余弦。

2

double sin(double);

该函数返回弧度角(double 型)的正弦。

3

double tan(double);

该函数返回弧度角(double 型)的正切。

4

double log(double);

该函数返回参数的自然对数。

5

double pow(double, double);

假设第一个参数为 x,第二个参数为 y,则该函数返回 x 的 y 次方。

6

double hypot(double, double);

该函数返回两个参数的平方总和的平方根,也就是说,参数为一个直角三角形的两个直角边,函数会返回斜边的长度。

7

double sqrt(double);

该函数返回参数的平方根。

8

int abs(int);

该函数返回整数的绝对值。

9

double fabs(double);

该函数返回任意一个浮点数的绝对值。

10

double floor(double);

该函数返回一个小于或等于传入参数的最大整数。

下面是一个关于数学运算的简单实例:

实例

#include iostream>

#include cmath>

using namespace std;

int main ()

{

// 数字定义

short s = 10;

int i = -1000;

long l = 100000;

float f = 230.47;

double d = 200.374;

// 数学运算

cout "sin(d) :" sin(d) endl;

cout "abs(i) :" abs(i) endl;

cout "floor(d) :" floor(d) endl;

cout "sqrt(f) :" sqrt(f) endl;

cout "pow( d, 2) :" pow(d, 2) endl;

return 0;

}

当上面的代码被编译和执行时,它会产生下列结果:

sin(d) :-0.634939 abs(i) :1000 floor(d) :200 sqrt(f) :15.1812 pow( d, 2 ) :40149.7

C++ 随机数

在许多情况下,需要生成随机数。关于随机数生成器,有两个相关的函数。一个是 rand(),该函数只返回一个伪随机数。生成随机数之前必须先调用 srand() 函数。

下面是一个关于生成随机数的简单实例。实例中使用了 time() 函数来获取系统时间的秒数,通过调用 rand() 函数来生成随机数:

实例

#include iostream>

#include ctime>

#include cstdlib>

using namespace std;

int main ()

{

int i,j;

// 设置种子

srand( (unsigned)time( NULL ) );

/* 生成 10 个随机数 */

for( i = 0; i < 10; i++ )

{

// 生成实际的随机数

j= rand();

cout "random number: " j endl;

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Random Number: 1748144778 Random Number: 630873888 Random Number: 2134540646 Random Number: 219404170 Random Number: 902129458 Random Number: 920445370 Random Number: 1319072661 Random Number: 257938873 Random Number: 12 56201101 random number: 580322989

Transferred from rookie tutorial

Guess you like

Origin blog.csdn.net/linux_huangyu/article/details/131973803