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限定符:限定一個變量爲只讀。