例:程序中的数据类型、常量、变量
#include <stdio.h>
int main( )
{
float f,m;
printf("length in feet: ");
scanf("%f", &f);
m = f / 3.28;
printf("equal to %f meters.\n", m);
return 0;
}
列出当前系统中各种类型数据占用的字节数
#include <stdio.h>
int main( )
{
printf("Size of int is: %d\n",sizeof(int));
printf("Size of short int is: %d\n",sizeof(short));
printf("Size of long int is: %d\n",sizeof(long));
printf("Size of unsigned int is: %d\n",sizeof(unsigned int));
printf("Size of float is: %d\n",sizeof(float));
printf("Size of double is: %d\n",sizeof(double));
printf("Size of long double is: %d\n",sizeof(long double));
printf("Size of char is: %d\n",sizeof(char));
return 0;
}
程序中慎重直接使用常量——用符号常量替代
#include <stdio.h>
#define PI 3.1415926 //定义符号常量
int main ( )
{
float r,l,s,sq,vq;
printf("please enter r,h:");
scanf("%f %f"), &r, &h);
l=2* PI *r;
s=r*r* PI;
sq=4* PI *r*r;
……
}
对比
/*不用符号常量的程序,注意若的错误*/
#include <stdio.h>
int main ( )
{
float r,l,s,sq,vq;
printf("please enter r,h:");
scanf("%f %f"), &r, &h);
l=2* 3.1415926 *r;
s=r*r* 3.1415926;
sq=4* 3.1445926 *r*r;
……
}
再品符号常量
//程序的问题:可读性差、难维护
#include <stdio.h>
int main ( )
{
int n, age, total;
scanf("%d %d", &age, &n);
if(age<30)
{
total=n*30;
printf("total=%d\n",total);
}
else
{
printf("done!\n");
}
return 0;
}
改进的代码:
#include <stdio.h>
#define PRICE 30 //代表固定的单价
#define AGE 30 //代表年龄
int main ( )
{
int n, age, total;
scanf("%d %d", &age, &n);
if(age<AGE) //30岁以下的才可以买
{
total=n*PRICE;
printf("total=%d\n",total);
}
else
{
printf("done!\n");
}
return 0;
}