一、基本框架
#include <iostream>
using namespace std;
int main()
{
system("pause");
return 0;
}
二、输出Hello World
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World" << endl;
cout << "hello c++" << endl;
system("pause");
return 0;
}
三、常量的定义方法
1.#define 宏常量:#define 常量名 常量值
- 通常在文件上方定义,表示一个常量
2.const修饰的变量:const 数据类型 常量名 = 常量值
- 通常在变量定义前加关键字const,修饰该变量为常量,不可修改
四、标识符命名规则
- 标识符不能是关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须为字母或下划线
- 标识符中字母区分大小写
五、整型
#include <iostream>
using namespace std;
int main()
{
//整型:short(2个字节) int(4个字节) long(4个字节) long long(8个字节)
//可以利用sizeof求出数据类型占用内存大小
//语法:sizeof(数据类型/变量)
short num1 = 10;
cout << "short占用内存空间为:" << sizeof(num1) << endl;
int num2 = 10;
cout << "int占用内存空间为:" << sizeof(int) << endl;
long num3 = 10;
cout << "long占用内存空间为:" << sizeof(long) << endl;
long long num4 = 10;
cout << "long long占用内存空间为:" << sizeof(long long) << endl;
//整型结论:short<int<=long<=long long
system("pause");
return 0;
}
六、实型(浮点型)
作用:用于表示小数
两者的区别在于表示的有效数字范围不同
数据类型 | 占用空间 | 有效数字范围 |
float | 4字节 | 7位有效数字 |
double | 8字节 | 15-16位有效数字 |
统计内存空间的方法
sizeof(数据类型或变量名)
表示小数的另一种方法:科学计数法
七、转义字符和字符串
C++中字符串有两种定义方法:
1.C风格字符串
char 变量名[] = "字符串";
注意:(1)需要在变量名后面加[](2)需要用双引号
2.C++风格字符串
string 变量名 = "字符串";
注意:需要在代码顶端引入头文件#include <string>
#include<iostream>
using namespace std;
#include <string> //C++风格字符串,要包含这个头文件
int main()
{
char ch = 'a';
cout << "ch=" << ch << endl;
char ch2 = 97;
cout << ch2 << endl;
char ch3 = 65;
cout << ch3 << endl;
cout << sizeof(char) << endl;
cout << (int)ch << endl;
//C风格字符串
char str[] = "zifuchuan";
cout << str << endl;
string str2 = "zifuchuan11";
cout << str2 << endl;
system("pause");
return 0;
}
八、运算符
在C++中使用运算符时需要用小括号提升优先级
int x = 10;
int y = 10;
cout << (x&&y) << endl;