C++笔记
我用的软件是Visual Studio Code,这是我目前已知最好用的软件
软件下载地址
一、c++基础
1.第一个程序
首先学习了用C++编写第一个程序HelloWorld
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
system("pause");//按任意键继续
return 0;
}
2.注释
在vscode中经常用到的快捷键:
Visual Studio Code注释快捷键注释快捷键:ctrl + k, ctrl + c
解除注释快捷键:ctrl + k, ctrl + u
#include<iostream>
using namespace std;
/*
多行注释:对这一段进行解释
main函数是程序的入口
main函数有且只能有一个
*/
int main()
{
cout << "Hello World!" << endl;//单行注释:对这一行进行解释,输出Hello World!
system("pause");
return 0;
}
3.变量
(像极了爱情,不停改变的值)
变量存在的意义:方便管理内存空间
怎么创建变量:数据类型 变量名 = 变量初始值
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << a << endl;
system("pause");
return 0;
}
4.常量
(程序中不可改变的数据,忠贞不渝)
两种定义常量的方式:
1.#define:宏定义常量
#define 常量名 常量值
2.const修饰的变量
const 数据类型 常量名 = 常量值
#include <iostream>
using namespace std;
#define day 7 //第一种方法
int main()
{
//day = 15;报错因为常量不可以修改
const int a = 10; //第二种方法
//a = 15;报错const修饰的变量也是常量
cout << day << " " << a << endl;
system("pause");
return 0;
}
5.关键字
这个不打重要,在后面的学习中慢慢就会都认识,不用背
6.标识符
标识符命名规则:(见名知意)
- 标识符不能是关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须是字母或下划线
- C++标识符区分大小写
7.数据的输入
从键盘上获取数据
语法:cin >> 变量;
数据的输出
语法:cout >> 变量;
二、数据类型
1.整形
数据类型存在意义:给变量分配合适的内存空间
short(短整型) int(整形) long(长整型) long long(长长整形)
#include <iostream>
using namespace std;
int main()
{
//1.短整型
short num1 = 10;
//2.整形
int num2 = 11;
//3.长整形
long num3 = 12;
//4.长长整型
long long num4 = 13;
cout << num1 << ' ' << num2 << ' ' << num3 << ' ' << num4 << endl;
system("pause");
return 0;
}
2.sizeof关键字
统计数据类型占用内存大小
语法:sizeof(数据类型/变量)
#include <iostream>
using namespace std;
int main()
{
//1.短整型
short num1 = 10;
cout << sizeof(short) << endl;
//2.整形
int num2 = 11;
cout << sizeof(int) << endl;
//3.长整形
long num3 = 12;
cout << sizeof(long) << endl;
//4.长长整型
long long num4 = 13;
cout << sizeof(long long) << endl;
system("pause");
return 0;
}
总结:short < int <= long <= long long
3.实型(浮点型)
默认情况下输出小数都是六位小数
- float(单精度)
- double(双精度)
#include <iostream>
using namespace std;
int main()
{
//1.单精度
float a = 3.14f;
//float a = 3.14;c++中默认小数都是double类型的,在赋值过程中进行了强制类型转换
cout << a << endl;
//2.双精度
double b = 3.14;
cout << b << endl;
//科学计数法
float c = 3e2;// 3 * 10 ^ 2;
float d = 3e-2;// 3 * 0.1 ^ 2;
cout << c << ' '<< d << endl;
system("pause");
return 0;
}
4.字符型
用于表示单个字符
语法:char ch = ‘a’;
#include <iostream>
using namespace std;
int main()
{
//1.字符型变量创建方式
char ch = 'a';
cout << ch << endl;
//2.字符型变量所占内存大小
cout << sizeof(char) << endl;
//3.字符型变量常见错误
//char ch1 = "a";创建字符型变量时要用单引号
//char ch2 = 'ssjdhks';创建字符型变量时单引号内只能有一个字符
//4.字符型变量对应的ASCII编码
cout << (int)ch << endl;
system("pause");
retur