解釋 C 語言中的變數宣告和變數規則


讓我們首先了解什麼是變數。

變數

  • 它是記憶體位置的名稱,可用於儲存資料值。

  • 變數在執行期間可能在不同時間取不同的值。

  • 變數名可以由程式設計師以有意義的方式選擇,以便反映其在程式中的功能(或)性質。

例如,sum、avg、total 等。

變數命名規則

下面解釋了變數命名的規則:

  • 它們必須以字母開頭。

  • 變數的最大長度在 ANSI 標準中為 31 個字元。但是,許多編譯器只識別前八個字元。

  • 大小寫字母不同。例如:total、TOTAL、Total 是 3 個不同的變數。

  • 變數不能是關鍵字。

  • 不允許使用空格。

變數宣告

下面解釋了關於變數宣告的語法和示例:

語法

以下是變數宣告的語法:

Datatype v1,v2,… vn;

其中,v1、v2、...vn 是變數的名稱。

例如,

int sum;
float a,b;

變數可以透過兩種方式宣告:

  • 區域性宣告 - “區域性宣告”是在主塊內宣告一個變數,其值在該塊內可用。

  • 全域性宣告 - “全域性宣告”是在主塊外宣告一個變數,其值在整個程式中可用。

示例

以下是 C 語言中變數的區域性和全域性宣告的 C 程式:

int a, b; /* global declaration*/
main ( ){
   int c; /* local declaration*/
   - - -
}

示例

下面是一個 C 程式,用於查詢商品的售價 (SP) 和成本價 (CP):

 線上演示

#include<stdio.h>
int main(){
   float CostPrice, SellingPrice, Amount; //variable declaration
   //costprice & sellingprice are variables and
   //float is a datatype
   printf("
product cost price: ");    scanf("%f", &CostPrice);    printf("
product selling price : ");    scanf("%f", &SellingPrice);    if (SellingPrice > CostPrice){       Amount = SellingPrice - CostPrice;       printf("
Profit Amount = %.4f", Amount);    }    else if(CostPrice > SellingPrice){       Amount = CostPrice - SellingPrice;       printf("
Loss Amount = %.4f", Amount);    }    else       printf("
No Profit No Loss!");    return 0; }

輸出

輸出如下:

product cost price : 240
product selling price : 280
Profit Amount = 40.0000

更新於: 2021 年 3 月 15 日

11K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.