数组(Arrays)
宣告方式 type 變數名[size]; ,如:
float salaries[4];
則salaries[0]~salaries[3]為其 Array的範圍
字符串(Strings)
C沒有內建的string type,string是由 char array 創造出來的,其中一個特別的限制是,special character ‘\0’用來指示一個string的結尾。
所以有當你的string 的length是5的時候,為了加一個’\0’ ,所以整個 array 長度一開始在宣告時,必須要至少長度6以上。
char name[4];
name[0]=’s’;
name[1]=’a’;
name[2]=’m’;
name[3]=’\0’ ==> 這個char 被遺忘的話,會造成string 的長度出現預料外的效果
此外 C 不允許一個数组被赋值(assign)到另一個数组,如:
Name =”sam” 是不允許的
所以我們要把一個字符串赋值到 char array的話,就可以直接使用standardlibrary中的function, strcpy()
strcpy(name,”sam”);
输入字符串
fgets(name,sizeof(name),stdin);
fgets會將輸入的值自动加入 ‘\n’ 所以name的長度,就會+1了
比如說會成這樣…
name[0] = ‘s’
name[1]= ‘a’
name[2]= ‘m’
name[3]=’\0’
name[4]=’\n’
如何解決?
name[strlen(name)-1]= ‘\0’
ex:
#include <stdio.h>
#include <string.h>
int main()
{
char line[100];
charfirst[50];
charlast[50];
printf("Enteryour first name\n");
fgets(first,sizeof(line),stdin);
printf("Enteryour last name\n");
fgets(last,sizeof(last),stdin);
first[strlen(first)-1]= '\0';
last[strlen(last)-1]='\0';
strcpy(line, first);
strcat(line," ");
strcat(line,last);
printf("yourname is %s\n", line);
return 0;
}
如何輸入數字
先使用fgets(), 然後再使用sscanf 將自fgets()得到的string 化為數字
Ex:
fgets(line, sizeof(line), stdin);
sscanf(line, “%d”, &value1,&value2, …);
如:
#include <stdio.h>
#include <string.h>
int main()
{
char line[100];
float width;
float height;
float area;
printf("Pleaseenter width, height of this triangle\n");
fgets(line,sizeof(line),stdin);
sscanf(line,"%f%f", &width, &height);
area = width*height/2;
printf("thistriangle is %f\n", area);
return 0;
}
Types of Integers
C 允許編程者指定不同的Integers, 所以編程者可以將機器做最優化的運用。
其大小比較 short <= int <= long, 通常而言 long four bytes, short通常為2 bytes, 且 int 的話是 2 或 4 bytes, 視 machine 情況而定。
一個 unsigned short int 使用全部2 bytes, 16bits 來表示正數,而 signed shortint 使用15 bits表示數字部份,而1 bit 為正負號。
Types of Floats
Float通常使用4bytes,但如果是 double (precision) 的話,就通常為8 byte。
而 long double,在有些系統效果只如同 double 而有些系統則延伸了精準度。
Const Declarations
有時需要用到不變的數值時,則可使用 const, 用法:
const float PI= 3.14;
Hexadecimal and Octal Constants
Base 10 | Base8 | Base 16 |
6 | 06 | 0x6 |
9 | 011 | 0x9 |
15 | 017 | 0xF |
Operatorsfor Performing Shortcuts
++a 和 a=a+1 相同
A+=2 和 A=A+2 相同
Side Effects
A side effect is an operation that isperformed in addition to the main operation executed by the statement.
Size=5;
Result=++Size;
此式會先increase Size然後再assign size 的值給 result,
使用 ++x在C++的code時,會比較有效率,而對C 而言沒有差別
value=1;
result= (value++ *5) +(value++ *3);
1. 將value*5, 然後+1
2. 將value*3,然後+1
3. 將這二個結果相加
事實上,1和2是俱一樣優先權的,因此compiler 會選其中一項先執行,便會造成side effects
為了避免此種問題的產生,最好在用++x或- -x時,使用單獨一行。