1、导读代码:
#include<stdio.h>
#include<string.h> //strlen的头文件
#define DENSITY 61.4 //人体密度
int main()
{
float weight, volume;
int size ,letter;
char name[40];
printf("Hi! what's your first name?\n");
scanf("%s",name);
printf("What's your weight in pounds?\n");
scanf("%f",&weight);
size = sizeof name;
letter = strlen(name);
volume = weight/DENSITY;
printf("Well,%s,your volume is %2.2f cubic feet.\n", name , volume);
printf("Also, your first name has %d letter,\n",letter);
printf("and we have %d bytes to store it.\n",size);
return 0;
}
结果:
注意:
- 用%s转换说明来处理字符串的输入和输出
- Scanf函数中的name前面没有&号,但是weight有,因为本身name就已经是地址了。
- C语言中用strlen()函数来得到数组中存储的个数。
- sizeof函数后面圆括号在这里省略了,在2中解释。
2、strlen函数
sizeof会以字节为单位给出对象的大小,strlen给出字符串中的字符长度,至于sizeof后面是否使用圆括号取决于运算对象是类型还是特定量,当为类型的时候,圆括号必不可少,但是特定量的时候,可有可无。不过建议都用上圆括号。
演示代码:
//如果编译器不识别%zd换成%u或者%ld
#include<stdio.h>
#include<string.h>
#define PRAISE "You are an extraordinary being"
int main(void)
{
char name[40];
printf("Enter your name: ");
scanf("%s",name);
printf("name = %s ,PRAISE = %s\n",name, PRAISE);
printf("name占用的字节数为%zd,但是用到的仅仅为%zd\n", sizeof(name),strlen(name));
printf("实际的PRAISE有字节%zd个,但是总占用的字节数是%zd",strlen(PRAISE),sizeof PRAISE);
return 0;
}
结果是:
结果中看到PRAISE一共有30个字符,但是占用了31个字节,原因是用“”号括起来的内容C语言自动当成字符串来处理,在最后加一个‘\0’作为结尾,内容表示为null,所以最后其实还有一个不现实的字节存’\0’。
3、常量和C预处理器
常量是指不变的量,其中#define规定的量叫明示常量也叫编译时替代:
#define NAME value
中在编译的时候会把NAME替换成value中的值。
示例代码:
//求pizza的面积和周长:
#include<stdio.h>
#define PI 3.14159
int main(void)
{
float area, circum, redium;
printf(" What is the radium of your pizza?\n");
scanf("%f", &redium);
area = redium *redium *PI;
circum = 2.0 * PI * redium;
printf("Circumference = %1.2f ,area = %1.2f \n",circum, area);
return 0;
}
结果是:
其中define还可以定义字符和字符串常量。
4、const限定符:限定一个变量为只读。