
首先让我们了解一下什么是变量。
它是用来存储数据值的内存位置的名称。
变量在执行过程中可以在不同的时间点取不同的值。
程序员可以选择有意义的变量名称,以反映其在程序中的功能或性质。
立即学习“C语言免费学习笔记(深入)”;
例如,sum(总和),avg(平均值),total(总计)等。
变量命名的规则如下所示:
变量名必须以字母开头。
在ANSI标准中,变量的最大长度为31个字符。但是,许多编译器只考虑前八个字符。
大小写字母是不同的。例如:total、TOTAL、Total是3个不同的变量。
变量名不能是关键字。
不允许使用空格。
下面是变量声明的语法和示例:
变量声明的语法如下所示:
Datatype v1,v2,… vn;
Where, v1, v2,...vn are names of variables.
For example,
int sum; float a,b;
变量可以通过两种方式进行声明 −
局部声明 − ‘局部声明’ 是在主代码块内部声明变量,其值只在该代码块内有效。
全局声明 − ‘全局声明’ 是在主代码块外部声明变量,其值在整个程序中都有效。
以下是C语言中局部和全局变量声明的示例程序 −
int a, b; /* global declaration*/
main ( ){
int c; /* local declaration*/
- - -
}以下是一个用于查找商品的售价(SP)和成本价(CP)的C程序 −
在线演示
#include<stdio.h>
int main(){
float CostPrice, SellingPrice, Amount; //variable declaration
//costprice & sellingprice are variables and
//float is a datatype
printf("</p><p> product cost price: ");
scanf("%f", &CostPrice);
printf("</p><p> product selling price : ");
scanf("%f", &SellingPrice);
if (SellingPrice > CostPrice){
Amount = SellingPrice - CostPrice;
printf("</p><p> Profit Amount = %.4f", Amount);
}
else if(CostPrice > SellingPrice){
Amount = CostPrice - SellingPrice;
printf("</p><p> Loss Amount = %.4f", Amount);
}
else
printf("</p><p> No Profit No Loss!");
return 0;
}输出如下 −
product cost price : 240 product selling price : 280 Profit Amount = 40.0000
以上就是解释变量声明和C语言中变量的规则的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号