- 新增现代 C++ 教程的 Preface 章节,包括英文和中文版本 - 添加 C++ Primer 练习代码 - 新增 Learn C++ 教程的 C++ 开发简介章节 - 添加头文件解析文档 - 更新 mkdocs.yml,包含新教程的目录结构 - 修改项目设置,使用 Python 3.10环境
1.4 KiB
1.4 KiB
C++的常量
1. 常量
① 常量,用于记录程序中不可更改的数据。
② C++定义常量两种方式,如下所示:
- #define 宏常量:#define 常量名 常量值
- note:通常在文件上方定义,表示一个常量。
- const修饰的变量 const 数据类型 常量名 = 常量值
- note:通常在变量定义前加关键字const,修饰该变量为常量,不可修改。
1.1 #define 常量名 常量值
#include <iostream>
using namespace std;
#define Day 7
int main()
{
/*
Day = 14; //错误,Day是常量,一旦修改就会报错
cout << "一周总共有:" << Day << "天" << endl;
*/
cout << "一周总共有:" << Day << "天" << endl;
// 输出语句:cout << "提示语" << 变量 << endl;
system("pause");
return 0;
}
运行结果:
- 一周总共有:7天
- 请按任意键继续. . .
1.2 const 数据类型 常量名 = 常量值
#include <iostream>
using namespace std;
int main()
{
/*
const int month = 12;
month = 24; //错误,const修饰的变量也称为常量
*/
int month = 12;
month = 24; //正确,这样可以修改变量的值
cout << "一年总共有:" << month << "个月" << endl;
system("pause");
return 0;
}
运行结果:
- 一年总共有:24个月
- 请按任意键继续. . .