第十一课:常量
学习目标:
常量的概念
字面量常量
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.14159
int 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.14159
int 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.