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

公眾號
微信公眾號

編程獅公眾號