C 常量

2018-05-20 10:41 更新

学习C - C常量

定义命名常量

PI是一个数学常数。我们可以将Pi定义为在编译期间要在程序中被其值替换的符号。


    #include <stdio.h> 
    #define PI   3.14159f                       // Definition of the symbol PI 

    int main(void) 
    { 
      float radius = 0.0f; 
      float diameter = 0.0f; 
      float circumference = 0.0f; 
      float area = 0.0f; 
      
      printf("Input the diameter of a table:"); 
      scanf("%f", &diameter); 
      
      radius = diameter/2.0f; 
      circumference = 2.0f*PI*radius; 
      area = PI*radius*radius; 
      
      printf("\nThe circumference is %.2f. ", circumference); 
      printf("\nThe area is %.2f.\n", area); 
      return 0; 
    } 

上面的代码生成以下结果。

注意

上面代码中的以下代码定义了PI的常量值。

#define PI   3.14159f                       // Definition of the symbol PI 

这将PI定义为要由代码中的字符串3.14159f替换的符号。

在C编写标识符是一个常见的约定,它们以大写字母显示在#define指令中。

在引用PI的情况下,预处理器将替换您在#define伪指令中指定的字符串。

所有替换将在编译程序之前进行。

我们还可以将Pi定义为变量,但是要告诉编译器它的值是固定的,不能被更改。

当您使用关键字const为类型名称前缀时,可以修改任何变量的值。

例如:

const float Pi = 3.14159f;                  // Defines the value of Pi as fixed 

这样我们可以将PI定义为具有指定类型的常数数值。

Pi的关键字const导致编译器检查代码是否不尝试更改其值。


const

您可以在上一个示例的变体中使用一个常量变量:


#include <stdio.h> 

int main(void) 
{ 
  float diameter = 0.0f;                    // The diameter of a table 
  float radius = 0.0f;                      // The radius of a table 
  const float Pi = 3.14159f;                // Defines the value of Pi as fixed 
  
  printf("Input the diameter of the table:"); 
  scanf("%f", &diameter); 
  
  radius = diameter/2.0f; 
  
  printf("\nThe circumference is %.2f.", 2.0f*Pi*radius); 
  printf("\nThe area is %.2f.\n", Pi*radius*radius); 
  return 0; 
} 

上面的代码生成以下结果。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号