优秀的编程知识分享平台

网站首页 > 技术文章 正文

C++笔记:定义常量和变量(c++中如何定义常量)

nanyue 2024-07-18 22:18:50 技术文章 9 ℃

1. 定义常量的方法

1.1 const 常量

 const int Month = 12;
 Month = 10;

此时输出就会报错,因为const已经限制了,无法再对Month赋值

1.2 宏常量

 #define Day 7;
 Day = 8;

同理也会报错

2 数据类型

2.1 整型

1.short ±2^15-1

2.int ±2^31-1

3.long ±2^31-1

4.long long ±2^61-1

2.2 sizeof关键字

计算数据类型所占大小

sizeof括号里的东西既可以是数据类型也可以是定义的数据

 short a = 10;
 cout << sizeof(short) << endl;
 short a = 10;
 cout << sizeof(a) << endl;

两种输出结果一致

2.3 实型(浮点型)

数据类型

占用空间

有效数字范围

float

4字节

7位有效数字

double

8字节

15-16位有效数字

用float时在小数后加f

2.4 字符型

 char ch = 'a';

c和c++中字符型变量只占用一个字节

 cout << sizeof(char) << endl;

结果为1

字符型变量并不是把字符本身放到内存中存储,而是把相应的ASCII编码放入存储单元

 char ch = 'a'; 
 cout << (int)ch << endl;

此时输出结果就是a对应的ASCII代码

2.5 转义字符

转义字符

含义

\a

警报

\n

换行

\t

水平制表

\\

代表一个反斜杠

\v

垂直制表

2.6 字符串型

2.6.1 C++风格字符串

数据类型:string

 #include<iostream>
 using namespace std;
 #include<string>
 int main()
 {
 string str = "helloWorld";
 cout << str << endl;
 return 0;
 }

双引号,并且要加#include<string>的头文件

2.6.2 C风格字符串

 char str1[] = "helloWorld";
 cout << str1 << endl;

双引号,并且加了中括号

2.7 bool类型

bool类型占一个字节大小

仅两个值:

true---真(1)

false---假(0)

 bool a = true;
 cout << a << endl;
 a = false;
 cout << a << endl;

输出结果为1,0

最近发表
标签列表