W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
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)致編譯器檢查代碼是否不嘗試更改其值。
您可以在上一個(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é)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: