解释 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP