解释 C 语言中的变量声明和变量规则

cserver side programmingprogramming

首先让我们了解一下什么是变量。

变量

  • 它是用于存储数据值的内存位置的名称。

  • 变量在执行期间的不同时间可能采用不同的值。

  • 程序员可以以有意义的方式选择变量名,以反映其在程序中的功能(或)性质。

例如,sum、avg、total 等。

变量命名规则

变量命名规则如下 −

  • 它们必须以字母开头。

  • 变量的最大长度为ANSI 标准中有 31 个字符。但是,许多编译器都认为前八个字符很重要。

  • 大小写字符不同。例如:total、TOTAL、Total 是 3 个不同的变量。

  • 变量不能是关键字。

  • 不允许使用空格。

变量声明

变量声明的语法和示例如下 −

语法

下面给出了变量声明的语法 −

数据类型 v1,v2,… vn;

其中,v1、v2、...vn 是变量的名称。

例如,

int sum;
float a,b;

变量可以用两种方式声明 −

  • 局部声明 − "局部声明"是在主块内声明一个变量,其值在该块内可用。

  • 全局声明 − "全局声明"是在主块外声明一个变量,其值在整个程序中都可用。

示例

以下是 C 语言中局部和全局声明变量的 C 程序 −

int a, b; /* 全局声明*/
main ( ){
   int c; /* 局部声明*/
   - - -
}

示例

下面给出一个 C 程序,用于查找商品的销售价格 (SP) 和成本价格 (CP) −

#include<stdio.h>
int main(){
   float CostPrice, SellingPrice, Amount; //变量声明
   //costprice & sellingprice 是变量,
   //float 是数据类型
   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

相关文章