首页 > 编程语言 >c++primer第五章循环和关系表达式学习笔记

c++primer第五章循环和关系表达式学习笔记

时间:2024-09-11 22:51:39浏览次数:13  
标签:std main primer cout int c++ 第五章 using include

for循环

简单for循环

#include <iostream>
using namespace std;
int main()
{ // 5.1
  int i;
  for (i = 0; i < 5; i++)
    cout << "C++ knows loops. \n";
  cout << "C++ knows when to stop.\n";
  return 0;
}

for循环组成部分

#include <iostream>
using namespace std;
int main()
{
    //5.2
    cout << "Enter the starting countdown value: ";
    int limit;
    cin >> limit;
    int i;
    for (i = limit; i; i--)
        cout << "i = " << i << "\n";
    cout << "Done now that i = " << i << "\n";
    return 0;
}

 i = 0 自动类型转换成bool类型的false

表达式和语句

x = y = z = 0; 赋值操作从右往左

age = 100 是表达式

age = 100; 是语句

 for (expression, expression, expression)

      statement;

#include <iostream>
using namespace std;
int main()
{
  // 5.3
  int x;
  cout << "The expression x = 100 has the value ";
  cout << (x = 100) << endl;
  cout << "Now x = " << x << endl;
  cout << "The expression x < 3 has the  value ";
  cout << (x < 3) << endl;
  cout << "The expression x > 3 has the  value ";
  cout << (x > 3) << endl;
  cout.setf(ios_base::boolalpha);
  cout << "The expression x < 3 has the  value ";
  cout << (x < 3) << endl;
  cout << "The expression x > 3 has the  value ";
  cout << (x > 3) << endl;
  return 0;
}

for循环计算阶乘

#include <iostream>
using namespace std;
int main()
{
  // 5.4
  const int ArSize = 16;
  double factorials[ArSize];
  factorials[1] = factorials[0] = 1.0;
  int i;
  for (i = 2; i < ArSize; i++)
    factorials[i] = i * factorials[i - 1];
  for (i = 0; i < ArSize; i++)
    cout << i << "! = " << factorials[i] << endl;
  return 0;
}

ArSize 修改就可以快速获得所有的常数的修改

修改步长

#include <iostream>
using namespace std;
int main()
{
  // 5.5修改步长
  cout << "Enter an integer: ";
  int by;
  cin >> by;
  cout << "Counting by " << by << "s: \n";
  for (int i = 0; i < 100; i = i + by)
    cout << i << endl;
  return 0;
}

使用for循环访问字符串

#include <iostream>
using namespace std;
int main()
{
  // 使用for循环 访问字符串
  cout << "Enter a word: ";
  string word;
  cin >> word;

  for (int i = word.size() - 1; i >= 0; i--)
    cout << word[i];
  cout << "\nBye.\n";
  return 0;
}

递增操作符和递减操作符

#include <iostream>
using namespace std;
int main()
{
  int a = 20;
  int b = 20;

  cout << "a = " << a << "; b = " << b << "\n";
  cout << "a++ = " << a++ << "; ++b = " << ++b << endl;
  cout << "a = " << a << "; b = " << b << "\n";
  return 0;
}

 a++ 先给出表达式结果然后再加1; ++b 先加1然后用新的值来给出表达式结果

   副作用(side effect)和顺序点(sequence point)

    int guests = 9;

    while (guests++ < 10)

        printf("%d \n", guests);

    guests 和10 比较之后加1;对于类而言,前缀版本的效率更高

递增递减操作符和指针

#include <iostream>
using namespace std;
int main()
{
  double arr[5] = {21.1, 32.8, 23.4, 45.2, 37.4};
  double *pt = arr;

  ++pt;
  cout << pt << endl;
  cout << *pt << endl;
  // ++*pt;  //int 类型的++
  *pt++;
  cout << pt << endl;
  cout << *pt << endl;

  return 0;
}

组合赋值操作符

i = i + by  等价于     i += by

    int k = 5;

    k += 3;

    int *pa = new int[10];

    pa [4] = 12;

    pa [4] +=6; 

    *(pa + 4) += 7;

    pa += 2;

    a += b  等价于   a = a + b

    a -= b  等价于   a = a - b

    a *= b 等价于    a = a * b

    a /= b  等价于   a = a / b

    a %= b  等价于  a = a % b

复合语句

#include <iostream>
using namespace std;
int main()
{
  // program5.8
  cout << "The Amazing Account will sum and average ";
  cout << "five numbers for you. \n";
  cout << "Please enter five values: \n";
  double number;
  double sum = 0.0;
  for (int i = 1; i <= 5; i++)
  {
    cout << "Value " << i << ": ";
    cin >> number;
    sum += number;
  }
  cout << "Five exquisite choices indeed! ";
  cout << "They sum to " << sum << endl;
  cout << "and average to " << sum / 5 << ".\n";
  cout << "The Amazing Account bids you adieu!\n";
  return 0;
}

 

外部语句定义的变量在内部是被定义,反之是没有被定义的

int x = 20;
    {
        cout << x << endl;
        int x = 100;
        cout << x << endl;
    }
    cout << x << endl;
    return 0;

 逗号操作符

将两个表达式放在原来只能放一个表达式的地方

#include <iostream>
using namespace std;
int main()
{
  cout << "Enter a word: ";
  string word;
  cin >> word;

  char temp; // 在外部声明变量可以提高速度
  int i, j;
  for (j = 0, i = word.size() - 1; j < i; --i, ++j)
  {
    temp = word[i];
    word[i] = word[j];
    word[j] = temp;
  }
  cout << word << "\nDone\n";
  return 0;
}

i = 20, j = 2 * i   逗号表达式的值是第二部分, 并且逗号表达式的优先级是最低的

关系表达式

 可能犯的错误

#include <iostream>
using namespace std;
int main()
{
    //== 等于, != 不等于 5.10
    int quizscores[10] =
        {20, 20, 20, 20, 20, 19, 20, 18, 20, 20};

    cout << "Doing it right: \ n";
    int i;
    for (i = 0; quizscores[i] == 20; i++)
        cout << "quiz " << i << " is a 20 \n";

    cout << "Doing it dangerously wrong: \n";
    for (i = 0; quizscores[i] = 20; i++)
        cout << "quiz " << i << " is a 20 \n";

    return 0;
}

 

C-风格字符串的比较

    word == "mate" 数组名是数组的地址,所以左边的判断表达式表示的是是否存储在相同的地址上。

    strcmp() 可以判断两个字符串是否相等

 不能关系操作符比较字符串,但是字符是整形所以 是可以比较的

  for (char ch = 'a'; ch < 'z'; ch++)
        cout << ch;
    return 0;

 

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char word[5] = "?ate";

    for (char ch = 'a'; strcmp(word, "mate"); ch++)
    {
        cout << word << endl;
        word[0] = ch;
    }
    cout << "After loop ends, word is " << word << endl;
    return 0;
}

 

strcmp(str1, str2) 如果这两个是不同的则输出是true,  同时还可以比较顺序

比较 string类字符串

#include <iostream>
#include <string>
using namespace std;
int main()
{
    // 5.12  比较 string类字符串
    string word = "?ate";

    for (char ch = 'a'; word != "mate"; ch++)
    {
        cout << word << endl;
        word[0] = ch;
    }
    cout << "After loop ends, word is " << word << endl;
    // C++ 使用String类型不用提前规定大小
}

while 循环

while 循环

    while(test-condition)

        body

#include <iostream>
const int ArSize = 20;
using namespace std;
int main()
{

    // 5.12
    char name[ArSize];
    cout << "Your first name: please: ";
    cin >> name;
    cout << "Here is your name: verticalized and ASCIIized: \n";
    int i = 0;
    while (name[i] != '\0')
    {
        cout << name[i] << ": " << int(name[i]) << endl;
        i++;
    }
    return 0;
}

for 循环可以知道所有的信息, while 循环无法预先知道所执行的次数

while (for) 后面加循环,则变成了空循环

等待一段时, 延时循环

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
    cout << "Enter the delay time, in second: ";
    float secs;
    cin >> secs;
    clock_t delay = secs * CLOCKS_PER_SEC;
    cout << "starting \a \n";
    clock_t start = clock();
    while (clock() - start < delay)
        ;
    cout << "done \a\n";
    return 0;
}

 

do while 循环

 do

       body

    while (test-expression)

 

#include <iostream>
using namespace std;
int main()
{
    int n;
    cout << "Enter numbers in the range 1-10 to find ";
    cout << "My favorite number\n";
    do
    {
        cin >> n;
    } while (n != 7);
    cout << "Yes, 7 is my favorite number. \n";
    return 0;
}

 循环和文本输入

cin输入

#include <iostream>
using namespace std;
int main()
{
    // 哨兵字符,作为停止标记
    char ch;
    int count = 0;
    cout << "Enter characters; Enter # to quit: \n";
    cin >> ch;
    while (ch != '#')
    {
        cout << ch;
        ++count;
        cin >> ch;
    }
    cout << endl
         << count << " characters read \n";
    return 0;
}

输出没有空格

cin.get()输入

修改代码

#include <iostream>
using namespace std;
int main()
{
    char ch;
    int count = 0;
    cout << "Enter characters; Enter # to quit: \n";
    cin.get(ch);
    while (ch != '#')
    {
        cout << ch;
        ++count;
        cin.get(ch);
    }
    cout << endl
         << count << " characters read \n";
    return 0;
}

cin.get()的两个使用方法

 文件尾条件

#include <iostream>
using namespace std;
int main()
{
    char ch;
    int count = 0;
    cin.get(ch);
    while (cin.fail() == false)
    {
        cout << ch;
        ++count;
        cin.get(ch);
    }
    cout << endl
         << count << "characters read \n";
    return 0;
}

 嵌套和二维数组

二维数组每一个元素本身就是一个数组。

#include <iostream>
using namespace std;
const int Cities = 5;
const int Years = 4;
int main()

{
    // 二维数组初始化,逗号隔开
    const char *cities[Cities] = // 字符串类型指针
                                 // char cities[Cities][25] =
                                 //     const string cities[Cities] =
        {
            "Gribble City",
            "Gribble town",
            "New Gribble",
            "San Gribble",
            "Gribble Vista"};
    int maxtemps[Years][Cities] =
        {
            {54, 53, 86, 100, 104},
            {95, 97, 90, 106, 102},
            {96, 100, 940, 107, 105},
            {97, 102, 89, 108, 104}};
    cout << "Maximum temperatures for 2002-2005 \n\n";
    for (int city = 0; city < Cities; ++city)
    {
        cout << cities[city] << ":\t";
        for (int year = 0; year < Years; ++year)
            cout << maxtemps[year][city] << "\t";
        cout << endl;
    }
    return 0;
}

标签:std,main,primer,cout,int,c++,第五章,using,include
From: https://blog.csdn.net/weixin_48442204/article/details/142072696

相关文章

  • C++primer 第十章对象和类学习笔记
    OPP特性:抽象封装和数据隐藏多态继承代码的可重用性过程性和面向对象的编程从用户的角度考虑对象抽象和类基本类型完成的工作:决定数据对象需要的内存单元决定如何解释内存中的位决定可使用数据对象执行的操作或方法 c++中的类类规范类声明:以数据成员的方式描述数......
  • 【C++】new的底层实现原理
    文章目录理解C++`new`的原理1.`new`的基本工作流程2.`new`和`malloc`的区别3.`new`的底层实现4.`new[]`与`delete`的配对使用5.自定义`new`和`delete`6.定位new7.内存泄漏与异常安全理解C++new的原理在C++中,new操作符用于在堆上动态分......
  • 【C++】C++ 多态的底层实现原理
    文章目录1.多态的定义与作用2.虚函数与虚函数表(vtable)3.虚函数表(vtable)4.虚函数调用的底层过程5.内存布局中的虚函数指针6.多重继承中的虚函数表7.RTTI与动态类型识别1.多态的定义与作用多态指的是同一操作在不同对象上具有不同的表现。C++中多态分为两......
  • 递归(c++)
    递归1、斐波那契额数列基础代码#include<iostream>usingnamespacestd;intf(intn){ if(n==1)return1; if(n==2)return2; returnf(n-1)+f(n-2);}intmain(){ intn; cin>>n; cout<<f(n)<<endl; return0;}递归实现指数......
  • c++ 数字转化成 string
       ULONG转换成string方法1:使用std::to_string(C++11及更高版本)std::to_string是将数字转换为字符串的简单方式,适用于C++11及更高版本。#include<iostream>#include<string>intmain(){ULONGvalue=1234567890UL;//定义一个ULONG类型的值/......
  • c++ string 转换成 guid
      在C++中,将一个字符串转换为GUID(GloballyUniqueIdentifier)可以通过以下方法实现。GUID通常是128位(16字节)的标识符,以标准格式表示,例如:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx。在C++中,常用的库之一是WindowsAPI,它提供了处理GUID的相关功能。这里是一个示例代码,将字符串转换......
  • 【自用22.】C++类的静态数据成员以及静态成员函数
    需要获取总的人数,如何实现?方案一:使用全局变量,在构造函数中对这个全局变量进行修改具体代码如下:在Human.cpp中定义全局变量,并在构造函数中对人数进行增加操作#include"Human.h"#include<iostream>usingnamespacestd;intHumanCount=0;Human::Human(){ name......
  • C++复习day10
    智能指针为什么需要智能指针?#include<iostream>usingnamespacestd;intdiv(){ inta,b; cin>>a>>b; if(b==0) throwinvalid_argument("除0错误"); returna/b;}voidFunc(){ //1、如果p1这里new抛异常会如何? //2、如果p2这里new抛异常会......
  • C++ web框架:matt-42/lithium
    一、代码示例#include<lithium_http_server.hh>#include<lithium_pgsql.hh>#include"symbols.hh"usingnamespaceli;intmain(){//创建PostgreSQL数据库连接pgsql_databasedb=pgsql_database(s::host="localhost"......
  • C++中的数组,字符串数组,pair数组
    1.C++中的字符串数组: 2.C++中的常量数组 这个constpair<int,string>valueSymbols[]定义了一个常量数组,数组中的每个元素都是一个pair<int,string>类型的对象。pair是C++标准模板库(STL)中的一个模板类,用于将两个值组合成一个单一的对象。在这个特定的例子中,pair的第一个......