1.4 常量

38 阅读1分钟

常量

作用:用于记录程序中不可更改的数据。

C++定义常量两种方式

1.#define 宏常量:#define 常量名 常量值

通常在文件上方定义,表示一个常量。

2.const修饰的变量 const 数据类型 常量名 = 常量值

通常在变量定义前加关键字const,修饰该变量为常量,不可修改。

代码实战:

#include <iostream>
using namespace std;

//常量的定义方式
//1.#define 宏常量
//2.const修饰的变量

#define Day 7

int main() {

	cout << "一周总共有多少天:" << Day << "天" << endl;

	system("pause");

	return 0;
}

运行结果:

image.png 这样写为什么是错的? image.png 显示为表达式必须为可修改的左值

原因:Day是常量,一旦修改就会报错。

image.png

代码实战:

#include <iostream>
using namespace std;

//常量的定义方式
//1.#define 宏常量
//2.const修饰的变量

#define Day 7

int main() {
	//Day = 14;

	cout << "一周总共有多少天:" << Day << "天" << endl;
	//2.const修饰的变量
	const int month = 12;
	//month = 24;//此处报错,原因:const修饰的变量也称为常量
	cout << "一年总共有" << month << "个月份" << endl;
	system("pause");

	return 0;
}

运行结果:

image.png

总结:

image.png