C 常量

2018-05-20 10:41 更新

學(xué)習(xí)C - C常量

定義命名常量

PI是一個(gè)數(shù)學(xué)常數(shù)。我們可以將Pi定義為在編譯期間要在程序中被其值替換的符號(hào)。


    #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; 
    } 

上面的代碼生成以下結(jié)果。

注意

上面代碼中的以下代碼定義了PI的常量值。

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

這將PI定義為要由代碼中的字符串3.14159f替換的符號(hào)。

在C編寫標(biāo)識(shí)符是一個(gè)常見的約定,它們以大寫字母顯示在#define指令中。

在引用PI的情況下,預(yù)處理器將替換您在#define偽指令中指定的字符串。

所有替換將在編譯程序之前進(jìn)行。

我們還可以將Pi定義為變量,但是要告訴編譯器它的值是固定的,不能被更改。

當(dāng)您使用關(guān)鍵字const為類型名稱前綴時(shí),可以修改任何變量的值。

例如:

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

這樣我們可以將PI定義為具有指定類型的常數(shù)數(shù)值。

Pi的關(guān)鍵字const導(dǎo)致編譯器檢查代碼是否不嘗試更改其值。


const

您可以在上一個(gè)示例的變體中使用一個(gè)常量變量:


#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; 
} 

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)