第十一课:常量
学习目标:
- 了解什么是常量以及为什么要使用常量。
- 学习如何在C++中定义常量。
- 理解字面量常量、const关键字、宏定义
 学习内容:
-  常量的概念 - 概念: 常量是在程序执行过程中其值不会改变的量。使用常量可以提高程序的可读性和维护性。
 
-  字面量常量 - 概念: 直接在代码中出现的数值、字符或字符串等,如5,'a',"Hello, world!"。
- 代码示例:#include <iostream>int main() {std::cout << 100; // 100 是一个整型字面量常量std::cout << 'A'; // 'A' 是一个字符字面量常量std::cout << 3.14; // 3.14 是一个浮点型字面量常量return 0; }
- 预计输出效果:100A3.14
- 使用场景: 当需要在代码中直接使用一个固定值时。
 
- 概念: 直接在代码中出现的数值、字符或字符串等,如
-  const关键字 - 概念: const用来定义常量,一旦初始化后不能改变。
- 代码示例:#include <iostream>int main() {const int LIGHT_SPEED = 299792458; // 速度的值设置为常量std::cout << "The speed of light is " << LIGHT_SPEED << " m/s.";return 0; }
- 预计输出效果:The speed of light is 299792458 m/s.
- 使用场景: 当希望某个变量的值在程序运行过程中保持不变时。
 
- 概念: 
-  宏定义 - 概念: 使用预处理器定义的常量,格式为 #define。
- 代码示例:#include <iostream> #define PI 3.14159int main() {std::cout << "The value of PI is " << PI;return 0; }
- 预计输出效果:The value of PI is 3.14159
- 使用场景: 在编译前替换代码中所有的宏定义常量。
 
- 概念: 使用预处理器定义的常量,格式为 
练习题: 编写一个C++程序,使用const关键字定义地球的平均半径(地球半径 = 6371公里),计算并输出地球表面积(公式:4 * PI * radius * radius)。使用#define定义PI的值为3.14159。
答案:
#include <iostream>
#define PI 3.14159int main() {const int EARTH_RADIUS = 6371; // 地球半径double earthSurfaceArea = 4 * PI * EARTH_RADIUS * EARTH_RADIUS;std::cout << "The surface area of the Earth is " << earthSurfaceArea << " square kilometers.";return 0;
}
预计输出效果:
The surface area of the Earth is 510064471.909 square kilometers.
目录
 第十二课:指针强化