C++学习 基础知识与语法

本文详细介绍了C++的基础知识和语法,包括变量、运算符、复合类型(如数组和字符串)、循环(for和while)、分支语句(if和switch)、函数、递归以及结构体的使用。通过实例解析了C++中的输入输出、循环控制和数据处理,为初学者提供了清晰的学习路径。
摘要由CSDN通过智能技术生成

C++学习

一, 基础知识与语法

1.1 基本框架

#include <iostream>
using namespace std;

int main() 
{  
    cout << 'hello world' << endl;
   
    system('pause');

    return 0;
}
    

1.2 注释

//单行注释,一般放在一行代码的上方
/*多行注释,通常放在一段代码的上方*/

1.3 变量

1.3.1 变量创建
//数据类型 变量名 = 变量初始值
int a = 10;  //整数
double //带小数的值
1.3.2 常量与变量的区别
//常量的定义方式
//1.#define 宏常量,一般放在开头,例如要定义一个星期的天数
#define Day = 7 
//2.const修饰的变量,放在程序里
const int a = 12

    
//常量不可修改,修改会报错

1.4 运算符

1.4.1算数运算符
+对操作数实行加法操作
-对操作数实行减法操作
*将操作数相乘
/将第一个数除以第二个数
%生成第一个数除以第二个数后的余数
1.4.1.1 运算符优先级和结合性

优先级

+,-为同一级

*,/,%为同一级

**+,-**这一级低于==*,/,%==这一级

结合性

引例:float logs = 120 / 4 *5 ;

C++规定乘除的结合性是从左到右

说明引例中logs = 150

1.4.1.2 除法分支

除法运算符的行为取决于操作数的类型,若两个操作数都为整数,则将执行整数除法,若有一个为浮点值,则保留小数,结果为浮点数。

1.4.2 关系运算符

假设A = 0 ; B = 1

运算符描述实例
==检查两个操作数的值是否相等,如果相等则条件为真。(A==B)不为真。
!=检查两个操作数的值是否相等,如果不相等则条件为真。(A!=B)为真。
>检查左操作数的值是否大于右操作数的值,如果是则条件为真。(A>B)不为真。
<检查左操作数的值是否小于右操作数的值,如果是则条件为真。(A<B)为真。
>=检查左操作数的值是否大于或等于右操作数的值,如果是则条件为真(A>=B)不为真。
<=检查左操作数的值是否小于或等于右操作数的值,如果是则条件为真。(A<=B)为真
1.4.3 逻辑运算符

假设变量 A 的值为 1,变量 B 的值为 0,则

运算符描述实例
&&称为逻辑与运算符。如果两个操作数都非零,则条件为真。(A&&B)为假
||称为逻辑或运算符。如果两个操作数中有任意一个非零,则条件为真。(A || B )为真
称为逻辑非运算符。用来逆转操作数的逻辑状态。如果条件为真则逻辑非运算符将使其为假。!(A&&B)为真

1.5 复合类型

1.5.1 数组

创建数组可以使用声明语句,要指出一下三点

  • 存储在每个元素中的值的类型
  • 数组名
  • 数组中的元素数

通用格式如下

typename arrayname[arrysize];其中arraysize可以是常量,数值,或常量表达式,且必须是整型,也不能是变量。

==一下程序说明了数组的一些属性,包括声明数组,给数组元素赋值,初始化数组。

// arrayone.cpp -- small arrays of integers
#include <iostream>
int main()
{
    using namespace std;
    int yams[3];    // creates array with three elements
    yams[0] = 7;    // assign value to first element
    yams[1] = 8;
    yams[2] = 6;

    int yamcosts[3] = {20, 30, 5}; // create, initialize array
    return 0; 
}

数组初始化规则

int cards[4] = {1,2,3,4};  //ok
int hand[4];               //ok
hand[4] = {1,2,3,4};       //no
hand = cards;              //no
1.5.2 字符串

在数组中使用字符串:char 变量名[] = "字符串值"

可用索引访问数组中的各个字符串,下面是一个截短字符串的例子。

const int ArSize = 15;
char name[ArSize] = "C++owboy"
name[3] = '\0';

该程序将name[3]设置为空字符,这使得字符串在第三个字符后即结束,虽然数组中还有其他字符。

1.5.3 字符数组

引例:

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

    cout << "Enter your name:\n";
    cin >> name;
    cout << "Enter your favorite dessert:\n";
    cin >> dessert;
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
  
    return 0;
}

假设输入xvhao salad,结果如下

Enter your name:
xvhao salad
Enter your favorite dessert:
I have some delicious salad for you, xvhao.

那么问题来了:为啥我只要输入依次就行了捏?

这个例子是这样的:cin把xvhao作为第一个字符串,并把它放在数组中,把salad留在输入流中,因为cin在获取字符数组输入时只读取一个单词,读取后自动在结尾添加空字符。所以第二个cin在输入队列中搜索用户喜欢的甜点时,发现了留在输入流中的salad,因此读取了salad。

1.5.4 每次读取一行字符串输入

istream中的类提供了一些面向行的类成员函数:getline()和get()。

这两个函数都读取一行输入,直到到达换行符。随后,getline()将丢弃换行符,而get()将换行符保留在输入序列里。

1.5.4.1 gteline()

它读取整行,通过使用回车键输入的换行符确定输入结尾。

例:

// instr2.cpp -- reading more than one word with getline
#include <iostream>
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter your name:\n";
    cin.getline(name, ArSize);  // reads through newline
    cout << "Enter your favorite dessert:\n";
    cin.getline(dessert, ArSize);
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    return 0; 
}

结果:

Enter your name:
xv hao
Enter your favorite dessert:
apple pie
I have some delicious apple pie for you, xv hao.
1.5.4.2 get()

get()会将换行符保留,,假设我们连续两次使用get()

cin.get(name,ArSize)
cin.get(dessert,ArSize)

由于第一次调用后换行符留在队列中,则第二次调用时get()看到的第一个便是换行符,因此get()会认为已经到行尾。这时可以借助不带参数的get(),它可以读取下一个字符,即使是换行符。

例:

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

    cout << "Enter your name:\n";
    cin.get(name, ArSize).get(); // read string, newline
    cout << "Enter your favorite dessert:\n";
    cin.get(dessert, ArSize).get();
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    // cin.get();
    return 0;
Enter your name:
xv hao
Enter your favorite dessert:
apple pie
I have some delicious apple pie for you, xv hao.

1.6 for循环

基础用法:

//introducing the for loop
#include <iostream>
int main()
{
    using namespace std;
    int i;  // create a counter
//   initialize; test ; update
    for (i = 0; i < 5; i++)
        cout << "C++ knows loops.\n";
    cout << "C++ knows when to stop.\n";
    // cin.get();
    return 0;
}
C++ knows loops.
C++ knows loops.
C++ knows loops.
C++ knows loops.
C++ knows when to stop.
  1. 首先i = 5是循环的初始化部分,
  2. 然后是测试部分
  3. 然后进行执行操作
  4. 最后循环更新,使用++递增运算符,相当于i = i + 1
1.6.1 修改步长

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

更新表达式可以是任何有效的表达式

1.6.2 for循环访问字符串

程序清单:显示相反字符串

// forstr1.cpp -- using for with a string
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    cout << "Enter a word: ";
    string word;//字符串类
    cin >> word;

    // display letters in reverse order
    //size()获取字符串的字符数
    for (int i = word.size() - 1; i >= 0; i--)
        cout << word[i];
    cout << "\nBye.\n";
    // cin.get();
    // cin.get();
    return 0; 
}
Enter a word: animal
lamina
Bye.
1.6.3 循环执行多条语句与逗号运算符

执行多条操作方法:两个花括号来构造一条复合语句。

逗号运算符:在更改条件中可以用逗号对多个变量进行更改

例子:将字符数组中的字符顺序反转

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

    // physically modify string object
    char temp;
    int i, j;
    for (j = 0, i = word.size() - 1; j < i; i--, j++)
    { // start block
        temp = word[i];
        word[i] = word[j];
        word[j] = temp;
    } // end block
    cout << word << "\nDone\n";
    // cin.get();
    // cin.get();
    return 0;
}
Enter a word: animal
lamina
Bye.

1.7 while循环

while循环是没有初始化和更新部分的for循环,只要测试条件和循环体。

while (text-condition)
             {
             body1;
             body2
             }
             

1.8 分支语句

前面的循环属于程序的一种决策能力,决定循环是否继续。那么对于有选择的决策,C++通过if和swich语句来实现。

1.8.1 if语句

if语句与while相似

if (text-condition)
        statement;

示例:

// if.cpp -- using the if statement
#include <iostream>
int main()
{
    using std::cin;     // using declarations
	using std::cout;
    char ch;
    int spaces = 0;
    int total = 0;
    cin.get(ch);
    while (ch != '.')   // quit at end of sentence
    {
        if (ch == ' ')  // check if ch is a space
            ++spaces;
        ++total;        // done every time
        cin.get(ch);
    }
    cout << spaces << " spaces, " << total;
    cout << " characters total in sentence\n";
    // cin.get();
    // cin.get();
    return 0;
}
The balloonist was an airhead
with lofty goals.
6 spaces, 46 characters total in sentence

如果有很多选择,则可以用if else if else 结构

例子:猜数游戏

// ifelseif.cpp -- using if else if else
#include <iostream>
const int Fave = 27;
int main()
{
    using namespace std;
    int n;

    cout << "Enter a number in the range 1-100 to find ";
    cout << "my favorite number: ";
    do
    {
        cin >> n;
        if (n < Fave)
            cout << "Too low -- guess again: ";
        else if (n > Fave)
            cout << "Too high -- guess again: ";
        else
            cout << Fave << " is right!\n";
    } while (n != Fave);
    // cin.get();
    // cin.get();
    return 0;
}
Too high -- guess again: 37
Too high -- guess again: 31
Too high -- guess again: 28
Too high -- guess again: 27
27 is right!

1.8.2 swich语句(相当于多重if else)

例如,输入一个整数,输出该整数对应的星期几的英文表示:

#include <stdio.h>
int main(){
    int a;
    printf("Input integer number:");
    scanf("%d",&a);
    if(a==1){
        printf("Monday\n");
    }else if(a==2){
        printf("Tuesday\n");
    }else if(a==3){
        printf("Wednesday\n");
    }else if(a==4){
        printf("Thursday\n");
    }else if(a==5){
        printf("Friday\n");
    }else if(a==6){
        printf("Saturday\n");
    }else if(a==7){
        printf("Sunday\n");
    }else{
        printf("error\n");
    }
    return 0;
}
Input integer number:3
Wednesday

1.9 函数

1.8.1 使用有返回值的函数

例如sqrt()它返回平方根

// sqrt.cpp -- using the sqrt() function

#include <iostream>
#include <cmath>    // or math.h

int main()
{
    using namespace std;
   
    double area;
    cout << "Enter the floor area, in square feet, of your home: ";
    cin >> area;
    double side;
    side = sqrt(area);
    cout << "That's the equivalent of a square " << side 
         << " feet to the side." << endl;
    cout << "How fascinating!" << endl;
    return 0;
}
Enter the floor area, in square feet, of your home: 6.25
That's the equivalent of a square 2.5 feet to the side.
How fascinating!
1.8.2 函数变体

有些函数需要多项信息,则要多个参数,它们用逗号分开。

例如数学函数pow(),可以计算一个数的n次方。pow(5,8)表示计算58

1.8.3用户定义的函数

当我们要添加另一个用户定义的函数,和库函数一样,一般将原型放在main函数之前。并且将新函数的源代码放在main()的后面.

// ourfunc.cpp -- defining your own function
#include <iostream>
void simon(int);    // function prototype for simon()

int main()
{
    using namespace std;
    simon(3);       // call the simon() function
    cout << "Pick an integer: ";
    int count;
    cin >> count;
    simon(count);   // call it again
    cout << "Done!" << endl;
	// cin.get();
    // cin.get();
    return 0;
}

void simon(int n)   // define the simon() function
{
    using namespace std;

    cout << "Simon says touch your toes " << n << " times." << endl;
}                   // void functions don't need return statements

当编写函数有返回值时,在函数头中指出返回类型,在函数体尾使用return

下列程序将英石单位转为磅单位

// convert.cpp -- converts stone to pounds
#include <iostream>
int stonetolb(int);     // function prototype
int main()
{
    using namespace std;
    int stone;
    cout << "Enter the weight in stone: ";
    cin >> stone;
    int pounds = stonetolb(stone);
    cout << stone << " stone = ";
    cout << pounds << " pounds." << endl;
	// cin.get();
    // cin.get();
    return 0;
}

int stonetolb(int sts)
{
     return 14 * sts;
}

Enter the weight in stone: 15
15 stone = 210 pounds.

1.10 递归

概念:把一个复杂的问题转化为一个个的小问题,而小问题能转化为更简单的问题,直到达到递归的“终点”——递归边界。递归边界是递归问题的特殊案例或者简单的情况,通过递归边界向上一层一层的返回数据,结束递归。

以具体例子说明

  1. 实现用递归求阶乘
#include <iostream>
using namespace std;
int Leo(int n)
{
    int sum = 1;
    if(1 == n)//递归终止条件
    {
        return 1;
    }
    sum =n * Leo(n - 1);
    return sum;//返回阶乘的总和
}
int main()
{
    int num;
    cin >> num;//输入一个数
    cout << Leo(num) << endl;  //输出该数的阶乘
    return 0;
}
/*
*在求X的阶乘和时
*可以利用递归的思想
*把大问题转化成小问题
*再把小问题转化成更小的问题
*最后得解
*/
8
40320
  1. 求斐波那契数列第n项

//Fibonacci数列的第一项为0,第二项为1,后续的每一项是前两项的和
//该数列的前两项的比例趋于一个常量:1.168...,成为黄金分割 数列形如:0 1 1 2 3 5 8 13 21 34...
#include <iostream>
using namespace std;
long int Leo(long int n);
int main()
{
    long n;
    cin>>n;//求Fibonacci数列的第n项
    cout<<Leo(n)<<endl;
    return 0;
}
long int Leo(long int n)
{
  if(n==0 || n==1)
    return n;
  else
    return Leo(n-1)+Leo(n-2);
}
4
3

1.11 结构体

基本概念:结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

类和结构:他们唯一的区别就是,结构的默认访问类型是public,而类为private。

通常使用类来实现类描述,而把结构限制为只表示纯粹的数据类型。

通过结构体创建变量的方式有三种:

  • struct 结构体名 变量名
  • struct 结构体名 变量名 = {成员1值,成员2值}
  • 定义结构体时顺便创建变量

例子:类似于前几个星期学的python


#include <iostream>
using namespace std;
#include <string>
// 1、创建学生数据类型:学生包括(姓名,年龄,分数)
// 自定义数据类型,一些类型集合组成的一个类型
// 语法 struct 类型名称 { 成员列表 }
struct Student
{
    // 成员列表

    // 姓名
    string name;
    // 年龄
    int age;
    // 分数
    int score;

} s3; //结构体变量创建方式3


// 2、通过学生类型创建具体学生

int main()
{

    //结构体变量创建方式1

    struct Student s1;

    s1.name = "xvhao";
    s1.age = 18;
    s1.score = 100;

    cout << "name: " << s1.name << "age: " << s1.age << "score: " << s1.score << endl;

    //结构体变量创建方式2
    struct Student s2 = {"lisi", 19, 80};
    cout << "name: " << s2.name << "age: " << s2.age << "score: " << s2.score << endl;

    // 2.3 在定义结构体时顺便创建结构体变量

    s3.name = "wangwu";
    s3.age = 20;
    s3.score = 100;
    cout << "name: " << s3.name << "age: " << s3.age << "score: " << s3.score << endl;

    system("pause");

    return 0;
}
name: xvhaoage: 18score: 100
name: lisiage: 19score: 80
name: wangwuage: 20score: 100
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值