在C语言中,可以使用#define或const关键字来定义常量。
使用#define宏定义:
#include <stdio.h>
#define PI 3.14159
int main() {
float radius = 5;
float area = PI * radius * radius;
printf("Area of circle: %f\n", area);
return 0;
}
上述代码中,#define用于定义常量PI,在后续的代码中,可以直接使用PI代表3.14159。注意,#define并不是定义了一个变量,而是将代码中出现的PI替换为3.14159。
使用const关键字定义常量:
#include <stdio.h>
int main() {
const float PI = 3.14159;
float radius = 5;
float area = PI * radius * radius;
printf("Area of circle: %f\n", area);
return 0;
}
上述代码中,使用const关键字定义了一个浮点数常量PI,并在后续代码中使用。使用const关键字定义的常量具有数据类型,并且不能修改。
这两种定义常量的方式在功能上是等效的,选择使用哪种方式取决于个人习惯和代码风格。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C语言中重载函数的方法是什么