当前位置:网站首页>Chapter 5 Loops and Relational Expressions

Chapter 5 Loops and Relational Expressions

2022-08-11 05:46:00 Ah zink wire rope

本章知识点:

 for循环

 表达式和语句

 递增运算符和递减运算符——++和–

 组合赋值运算符

 复合语句

 逗号运算符

 关系运算符——>、>=、==、<=、<、!=

 while循环

 typedef工具

 do while循环

 Character input methodget()

 文件尾条件

 嵌套循环和二维数组

5.1 for循环

5.1.1 for循环的组成部分

声明模板:

for (initialization; test-expression; upadate-expression)
   body

例如:

int i;
for  (i = 0; i <5; i++ )
{
    }

forWhen there is only one statement in the loop,可以不用{},Just use indentation;多条时,必须使用{};for循环不加{}When only the first statement immediately following is in the loop,Indentation is ignored.

int i;
for (i = 0; i <5; i++ )
cout << “hello ” << endl;
cout << “C++ knows when to stop” <<endl;
//
int i;
for (i = 0; i <5; i++ )
{
    
  cout << “hello1 ” << endl;
  cout << “hello 2<< endl;
}
cout << “C++ knows when to stop” <<endl;

C++The program will put it where it expects an integer valuetrue和false分别转换为1和0,而在需要boolwhere the value will be0和非0分别转换为false和true.

int i;
for (i = 4; i; i-- )
{
    
..
}

Here will run toi=0.
cout在显示boolvalue before converting it toint,可调用

cout.setf(ios::boolalpha); 

The function sets a flag,The mark fame and fortunecout显示true和false,而不是0和1.
另外,for(int i = 0; I < 5; i++)也是允许的,只是iOnly exists in the loop body,局部变量.

5.1.5 递增运算符(++)和递减运算符(- -)

++x,表示使用x的当前值计算表达式,然后将x的值加1;**x++**表示先将x的值加1,然后使用新的值来计算表达式.
5.1.8 递增/递减运算符和指针
" * "(解除引用)and prefix decrement/Incrementing priorities are the same,以从右到左的方式进行结合;后缀递增/Decreasing priority is the same,But it has higher precedence than the prefix operator,Combine in a left-to-right fashion.
1)*++pt 2)++*pt 3)(*pt)++ 4) *pt++

# include <iostream>
int main(void)
{
    
  using namespace std;
  double arr[5] = {
    1.1, 2.1, 3.7, 4.9 . 5.8};
  double *pt = arr;
   
  cout << *pt << endl;      //1.1
  cout << *++pt << endl;    //2.1.注意,此处的++pt是全局的,will affect the next steppt.
  cout << ++*pt << endl;    //3.1 .Increase firstcout
  cout << (*pt)++ << endl;   //3.1.先cout后增加
  cout << *pt << endl;    //4.1
  cout << *pt++ << endl;   //4.1
  cout << *pt << endl;     //3.7.{1.1, 4.1, 3.7, 4.9, 5.8}
}
  1. 先执行++pt,Dereference again;
  2. Dereference the content first and then execute it++;
  3. Dereference it first++,此处先cout后再执行+1操作;
  4. ++优先级更高,所以先用pt,也就是先*pt(34.8),再执行+1;

5.1.11 其他语法技巧——逗号运算符

所有运算符中,逗号运算符的优先级最低;Relational operators have lower precedence than arithmetic operators,也就是说:x+3 > y-2 相当于是 (x+3)>(y-2).

5.1.14 C-风格字符串的比较

数组名是数组的地址,String constants enclosed in parentheses are also addresses,The storage address of the same string is also different.Therefore, neither arrays nor strings can be directly compared for equality directly through the array name or string.
字符串通过strcmp()函数(cstring)进行比较,The function receives two string addresses as parameters,That is, the parameter can be a pointer、字符串常量或字符数组名.如果两个字符串相同,该函数将返回0;If the first letter of the first string is alphabetically before the second string,返回一个负数值,Otherwise, a positive value is returned.

5.1.15 比较string类字符串

stringString-like comparisonC-Style strings are simpler to write,Comparisons can be made directly using relational operators.Because the class function overloads the operator.
string类重载!=运算符适用于:At least one operand isstring对象,另一个操作数可以是string对象,也可以是C-风格字符串.

5.2 while循环

while循环There is no initialization and update partfor循环,它只有测试条件和循环体.

while (test-condition)
     body

首先判断test-condition,为true则执行循环体中的语句.执行完循环体后,程序返回test-condition重新评估,If non-zero, execute the loop body again,直至test-condition为false.

# include <iostream>
Const int ArSize = 20;
int main(void){
    
   using namespace std;
   char name[ArSize] = 20;

   cout << ”Your first name :;
   cin >> name;

   cout << “Here is your name :<< endl;

   int i = 0;
   while(name[i] != ‘\0)      //while(name[i]),The second statement is more concise;The former code is cleaner and readable
{
    
     cout << name[i] <<:<< (int)name[i] << endl;
     i++;
}
}

5.2.1 for与while
C++中for和while本质相同,可以相互转换.
for循环→while循环

for (init-expression; test-expression; upadate-expression)
{
    
   statement(s)
}
//等价于
int-expression;
while (test-expression)
{
    
     statements(s);
     update-expression;
}

while循环→for循环

while (test-expression)
{
    
   statement(s)
}
//等价于
for ( ;test-expression; )
{
    
     statements(s);
}

for循环需要3个表达式,Expressions can be empty,But two semicolons are required.If the test expression is also empty,测试结果将为true,The loop will continue to run:

for ( ; ; )
{
    
     statements(s);
}

Often used when the number of loop executions cannot be predictedwhile循环.
Circular design guidelines:
 Specifies the condition under which the loop terminates
 Initialize the condition before the first test
 Update the condition before it is tested again
while循环和forA loop is the same as the expression enclosed in parentheses and the following loop body(Contains only one statement)组成.It is recommended to enclose the loop body statement with parentheses regardless of whether there is only one or more loop body statements.

5.2.2 等待一段时间:编写延时循环

应用场景:The program displays a message on the screen,But not before reading,Something else appeared.Uncontrollable by pure computer counting or counting too fast due to high machine performance,At this point, the system clock needs to be used to complete this kind of work.
函数clock(),返回程序开始执行后所用的系统时间.The return unit is not necessarily seconds,And the return type may be on some systemslong或者unsigned long.
头文件ctimnecan solve these problems,它定义了一个符号常量——CLOCKS_PER_SEC,该常量等于每秒钟包含的系统时间单位数.Hence the system time/ CLOCKS_PER_SECto get seconds;or the number of seconds* CLOCKS_PER_SECYou can get the time in system time units.
clock()返回类型为clock_t,Variables can be declared as clock_t类型,The compiler will convert it to long、unsigned intor other types suitable for the system.

# include <iostream>
# include <ctime>
int main(void)
{
    
   using namespace std;
   cout << “Enter the delay time ,in seconds”;

   float secs;
   cin >> secs;
   clock_t delay = secs * CLOCK_PER_SEC;
   
   clock_t start = clock();
  
   while(clock() – start) < delay)
;

cout << “done!\n”;
  
   return 0;
}

This program is in system time units(instead of seconds)计算延迟时间,避免了在每轮循环中将系统时间转换为秒.
类型别名
1、预处理器

#define BYTE char

用char替换所有的BYTE,BYTE成为char的别名.
2、关键字typedef

typedef typeName aliasName

Pointers also work:

typedef char * byte_pointer   //让byte_pointter成为char指针的别名

#defineNot applicable when declaring a series of variables.

#define FLOAT_POINTER float * 
FLOAT_POINTER pa, pb
//After preprocessing permutation transformation:
float *pa, pb   //pa为指针,而pb为float

相应的typedef:

typedef float * FLOAT_POINTER
FLOAT_POINTER pa, pb
After preprocessing permutation transformation:
float *pa, pb   //pa、pb皆为指针

统一用typedefAs a way to define variable aliases.
Type aliases improve code readability,Refer to the code on the previous pageint的别名clock_t,一目了然.

5.3 do while循环

语法:

do
     body
while(test-expression);

出口条件循环,首先执行循环体,再判定测试表达式,决定是否继续执行循环.
do whileLoops are often used for user input.

cin >> n ;
while(n != 7)
{
    
    cin >> n;
}
//可用do while更为简洁:
do 
{
    
   Cin >> n;
}while(n != 7)

5.4 基于范围的for循环(C++11)

double prices[5] = {
    1, 2, 3, 4, 5};
for(double x : prices)
   cout << x << endl;   //输出prices中的所有值

同样也可使用 for (int x : {3, 5, 6, 7})

5.5 循环和文本输入

5.5.1 使用原始的cin进行输入

The program uses a loop to read text input from the keyboard,encountering a certain character(哨兵字符)stop reading input.

cin >> ch

cin会忽略空格和换行符,So spaces in the input are not echoed,and will not be counted.

5.5.2 使用cin.get(char)进行补救

cin.get(char)The above problem can be remedied,You can assign to the next character even a spacech.

cin.get(ch)

5.5.4 文件尾条件

使用诸如#The etc symbol as the end of input is occasionally not well suited,Because the symbol may also be part of legal input.
End-of-file detection can be usedEOF技术.UNIXCan be pressed at the beginning of the lineCtrl+D实现;WIN命令提示符模式下,可以在任意位置按Ctrl+Z和Enter.The specific situation may vary.

5.6 嵌套循环和二维数组

C++没有提供二维数组类型,但用户可以创建每个元素本身都是数组的数组.
int temperature[4][5]
temperature是一个包含4个元素的数组,其中每个元素都是一个由5个整数组成的数组,4行5列.
for循环打印:

for (int row =0; row < 4; row ++)
{
    
   For (int col = 0; col < 5; ++ col)
        {
    
               Cout << temperature[row][col] << “\n”;
        }
    cout << endl; 
}

charEach element in an array of pointers is onechar指针,Can be initialized to the address of a string,例如:

const char * cities[5] = 
{
    
      “Gribble City”,
      “Grubbletown”,
      “New Gribble”,
}

This example can also be usedchar数组的数组,如下:

char cities[3][25] = 
{
    
      “Gribble City”,
      “Grubbletown”,
      “New Gribble”,
}

char指针和char数组的数组,从存储空间角度,It is more economical to use an array of pointers;But if you want to modify the string in it,It is more convenient to use a two-dimensional array.
此外,还可以使用string对象数组:

string cities[3][25] = 
{
    
      “Gribble City”,
      “Grubbletown”,
      “New Gribble”,
}

In the case where the string is modifiable,stringThe auto-sizing nature of the class makes this approach more convenient than using a two-dimensional array.

原网站

版权声明
本文为[Ah zink wire rope]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110512453025.html