1 / 76

C Program Design Data Types

C Program Design Data Types. 主講人:虞台文. Content. Memory Concept Number Systems Basic Data Types int char float Double Data-Type Modifiers Type Conversions. C Program Design Data Types. Memory Concept. CPU. ALU. Input Device. Output Device. Input. Output. Control. Memory.

garnet
Download Presentation

C Program Design Data Types

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C Program DesignData Types 主講人:虞台文

  2. Content • Memory Concept • Number Systems • Basic Data Types • int • char • float • Double • Data-Type Modifiers • Type Conversions

  3. C Program DesignData Types Memory Concept

  4. CPU ALU Input Device Output Device Input Output Control Memory Computer Architecture Memory

  5. 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 Data in Memory: Bit, Byte, Word, … • Bit: • 2 possible values • Byte: 8-bit data • 256 (28) possible values • Word: 16-bit data • 65536 (216) possible values 0/1

  6. C Program DesignData Types Number Systems

  7. 00000000 00000001 00000002 00000003 00000004 00000005 00000006 00000007 00000008 FFFFFFFB FFFFFFFC FFFFFFFD FFFFFFFE FFFFFFFF Memory Space address OS System Area mail User Area Word HelloWorld

  8. Number Systems Examples: • Binary (0-1) • bn1bn2…b2b1b0 • Octal (0-7) • on1on2…o2o1o0 • Decimal (0-9) • dn1dn2…d2d1d0 • Hexadecimal (0-9,A-F) • hn1hn2…h2h1h0

  9. Number System Conversion Examples: • Binary (0-1) • bn1bn2…b2b1b0 • Octal (0-7) • on1on2…o2o1o0 • Decimal (0-9) • dn1dn2…d2d1d0 • Hexadecimal (0-9,A-F) • hn1hn2…h2h1h0

  10. Number System Conversion Binary Octal Hexadecimal Decimal 0000 0 0 0 0001 1 1 1 0010 2 2 2 0011 3 3 3 0100 4 4 4 0101 5 5 5 0110 6 6 6 0111 7 7 7 1000 8 10 8 1001 9 11 9 1010 10 12 A 1011 11 13 B 1100 12 14 C 1101 13 15 D 1110 14 16 E 1111 F 15 17

  11. Number Coding in C #include <stdio.h> main() { int octNum = 011; // an octal number is prefixed by 0 int hexNum = 0x11; // a hexadecimal number is prefixed by 0x int decNum = 11; // a decimal number is w/o any prefix // display decimal numbers // for numbers represented in different number systems printf("011=%d, 0x11=%d, 11=%d\n", octNum, hexNum, decNum); // desplay a number using different number sytems printf("100=0x%x, 100=0%o, 100=%d\n", 100, 100, 100); }

  12. 0 1 1 1 0 0 1 1 Data Coding int totalMoney = 115; int motorState = 115; int girl_boy = 115; 11510 = 011100112 = 011100112 = 011100112 7 = 01112 3 = 00112

  13. 練習 • 輸入一介於0-255之十進位數字用於表示八台馬達之狀態(如前投影片所示),利用你目前所學過之C敘述撰寫一程式,輸出各台馬達之狀態。例:

  14. 練習 • 輸入一介於0-255之十進位數字用於表示男女孩數(如前投影片所示),利用你目前所學過之C敘述撰寫一程式,輸出男孩與女孩數。例:

  15. C Program DesignData Types Basic Date Types

  16. Basic Data Types The type of an object determines the set of values it can have and what operations can be performed on it.

  17. The sizeof Operator #include <stdio.h> main() { printf("The size of char is: %d\n", sizeof(char)); printf("The size of int is: %d\n", sizeof(int)); printf("The size of float is: %d\n", sizeof(float)); printf("The size of double is: %d\n\n", sizeof(double)); printf("The size of short is: %d\n", sizeof(short)); printf("The size of long is: %d\n", sizeof(long)); printf("The size of long double is: %d\n", sizeof(long double)); printf("The size of void* is: %d\n\n", sizeof(void *)); }

  18. int Signed Integer • The size of int is dependent on machine • It is usually the most efficient data type of a machine, e.g., in a 32-bit machine, its size is 32 bits, i.e., 4 bytes. • The range of int is defined in <limits.h> #defineINT_MIN (-2147483647 - 1) /* minimum (signed) int value */ #defineINT_MAX 2147483647 /* maximum (signed) int value */

  19. INT_MIN (-2147483647 - 1) INT_MAX 2147483647 int Signed Integer #include <stdio.h> #include <limits.h> main() { int val1, val2, val3, val4; printf("int range: %d <--> %d\n", INT_MIN, INT_MAX); val1 = INT_MIN + 1; val2 = INT_MAX - 1; // within range val3 = INT_MIN - 1; val4 = INT_MAX + 1; // overflow // ok --- within range printf("INT_MIN + 1 = %d, INT_MAX - 1 = %d\n", val1, val2); // overflow printf("INT_MIN - 1 = %d, INT_MAX + 1 = %d\n", val3, val4); }

  20. ASCII Integer Constants • Integer constant can be expressed in the following ways: 1234 (decimal) 0xff (Hexidecimal) 0100 (Octal) 'a' (ASCII character) '\xhh' (Hex character) '\000' (Oct character) Overflow 由程式設計師負責 用於表示一個 Byte足夠表示之整數

  21. ASCII Integer Constants #include <stdio.h> main() { int val1, val2, val3, val4; val1 = 'd'; val2 = '\x64'; val3 = '\144'; val4 = 'a' + 3; // Display in decimal printf("'d'=%d, '\\x64'=%d, '\\144'=%d, 'a' + 3 = %d\n", val1, val2, val3, val4); // Display in character printf("'d'->%c, '\\x64'->%c, '\\144'->%c , 'a' + 3->%c\n" val1, val2, val3, val4); }

  22. 練習 • 預測以下程式中哪些敘述編譯時會產生錯誤(error)或警訊(warning) , 說明其原因,編譯並驗證之。 #include <stdio.h> #include <limits.h> main() { int v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = INT_MAX + 1; v2 = INT_MIN - 1; v3= 9999999999999; v4 = -9999999999999; v5 = 0x100; v6 = '\x100'; v7 = 0377; v8 = '\377'; v9 = 0477; v10 = '\477'; }

  23. CHAR_MIN (-128) INT_MAX 127 char Signed Character • The size of char is 8 bits (1 byte) • Although it is named character, it is in fact an integer whose value can be represented by one byte, i.e., between 128 and +127. <limits.h> #define SCHAR_MIN (-128) /* minimum signed char value */ #define SCHAR_MAX 127 /* maximum signed char value */ // . . . . #define CHAR_MIN SCHAR_MIN #define CHAR_MAX SCHAR_MAX

  24. CHAR_MIN (-128) INT_MAX 127 char Signed Character • The size of char is 8 bits (1 byte) • Although it is named character, it is in fact an integer whose value can be represented by one byte, i.e., between 128 and +127. • It is most frequently used to represent ASCII characters (7-bit) ASCII

  25. ASCII Character Constants • Character constant can be expressed in the following ways: 1234 (decimal) 0xff (Hexidecimal) 0100 (Octal) 'a' (ASCII character) '\xhh' (Hex character) '\000' (Oct character) Overflow 由程式設計師負責 用於表示一個 Byte足夠表示之整數

  26. Character Constants • Some Escape Sequences

  27. 範例:Character Constants #include <stdio.h> main() { char c1, c2, c3, c4; c1 = 'd'; c2 = '\x64'; c3 = '\144'; c4 = 'a' + 3; // Display in decimal printf("'d'=%d, '\\x64'=%d, '\\144'=%d, 'a' + 3 = %d\n", c1, c2, c3, c4); // Display in character printf("'d'->%c, '\\x64'->%c, '\\144'->%c , 'a' + 3->%c\n" c1, c2, c3, c4); }

  28. ASCII 範例:Escape Sequences #include <stdio.h> main() { printf("\x6d\x6f\x64\x65\x6d\n"); }

  29. charvs.int • char與int可以說只有大小(容量)不同,可以用來存放相同性質之資料。 • 一般,sizeof(int) > sizeof(char)。 • 故,若容量足夠,使用char較省記憶體。例如:表示年齡(age)與各科成績(math_score)之變數,用char已足夠。 • 然,省記憶體不意謂運算速度較快。 • char與int變數間可以進行運算 • char變數將先轉為int型態後,再行運算,運算後型態為int • char與int資料型態之變數值可交互指派(可能overflow) • C中字串(string)係char形成之陣列。

  30. 範例:charvs.int • 以下程式可以通過編譯,但結果卻與預期不同 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2;// val = 800? printf("val = c * 2 = %d(Expected %d)\n", val, 800); c = val;// c = 800? printf("c = val = %d(Expected %d)\n", c, 800); }

  31. 範例:charvs.int • 以下程式可以通過編譯,但結果卻與預期不同 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2;// val = 800? printf("val = c * 2 = %d(Expected %d)\n", val, 800); c = val;// c = 800? printf("c = val = %d(Expected %d)\n", c, 800); }

  32. 練習 • 試找出產生是項執行結果之原因 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2;// val = 800? printf("val = c * 2 = %d(Expected %d)\n", val, 800); c = val;// c = 800? printf("c = val = %d(Expected %d)\n", c, 800); }

  33. 常用之字元輸出入函式 • int getchar ( void ); • Returns the next character from the standard input (stdin). • Remark: line-based read • int putchar ( int character ); • Writes character to the current position in the standard output (stdout) and advances the internal file position indicator to the next position.

  34. 範例:字元輸出入函式 /* uppercase typewriter */ #include <stdio.h> main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); }

  35. 範例:字元輸出入函式 /* uppercase typewriter */ #include <stdio.h> main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); }

  36. 200 bytes 記 憶 體 50 bytes 400 bytes 陣列(Arrays) score Array is a data structure that stores contiguous data elements of the same type. address distance Examples: int score[50]; char address[50]; double distance[50];

  37. score[0] score[1] . . . score[49] Examples: 陣列(Arrays) int score[50]; char address[50]; double distance[50]; score address distance

  38. address[0] address[1] address[2] . . . address[49] Examples: 陣列(Arrays) int score[50]; char address[50]; double distance[50]; score address distance

  39. . . . distance[0] distance[49] Examples: 陣列(Arrays) int score[50]; char address[50]; double distance[50]; score address distance

  40. 陣列使用注意事項 • 陣列之索引(index)由0開始 • 一陣列若含n元素,其索引由0至n-1 • C Compiler對陣列索引不做out of range檢查 • 易產生程式錯誤,甚或系統失敗 • 寫程式時程式設計師應保證陣列索引不超出範圍

  41. 範例: 輸入若干位學生成績將之儲存於一整數陣列中,並求算平均成績。 #include <stdio.h> #define MAX_STUDENTS 50 int scores[MAX_STUDENTS]; // define as global main() { int i, count=0, score, sum, avg;// local variables do{ // Enter scores until a negative score is obtained printf("Enter score for student No. %d:", count + 1); scanf("%d", &score); if(score >= 0) scores[count++] = score; } while(score >= 0 && count < MAX_STUDENTS); for(i = 0, sum = 0; i < count; sum += scores[i++]);// sum all scores avg = count > 0 ? sum / count : 0; // calc average printf("The average score of %d students is %d\n", count, avg); }

  42. 練習: • 修改此範例,使之於輸入所有成績完畢後,亦能將每位學生給予ABCDF等之評等,及其它數據,請自由發揮,輸出力求清晰。 #include <stdio.h> #define MAX_STUDENTS 50 int scores[MAX_STUDENTS]; // define as global main() { int i, count=0, score, sum, avg;// local variables do{ // Enter scores until a negative score is obtained printf("Enter score for student No. %d:", count + 1); scanf("%d", &score); if(score >= 0) scores[count++] = score; } while(score >= 0 && count < MAX_STUDENTS); for(i = 0, sum = 0; i < count; sum += scores[i++]);// sum all scores avg = count > 0 ? sum / count : 0; // calc average printf("The average score of %d students is %d\n", count, avg); }

  43. 範例:陣列之定義 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10];// specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); }

  44. 範例:陣列之定義 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10];// specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); } Debugging Mode執行結果

  45. 對未定義初值之陣列元素值勿做臆測 範例:陣列之定義 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10];// specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); } Release Mode執行結果

  46. h (68) e (65) l (6C) l (6C) o (6F) \n (0A) \0 (00) 字串(String) • C語言沒有定義字串資料型態 • C語言之字串係以零(NUL)作為結尾之字元陣列(char array)表示 • 例: str str[0] str[1] str[2] char str[]="hello\n"; str[3] str[4] str[5] str[6] sizeof(str) = 7

  47. 範例: 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1));// out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line }

  48. 範例: 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1));// out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line }

  49. 簡化版 範例: 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1));// out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line } do{ // read a line in safe mode line[i++] = c = getchar(); } while(c != '\n' && i < (MAX_LINE - 1));// out of range check by programmer while(c = line[i]) line[i++] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c;

  50. 練習: • 製作一C程式,從標準輸入裝置成功的讀取一十進制整數字串(可能含正負號) , 並將之儲存於一字元陣列中。 • 將上題儲存於陣列中之字串轉換成整數,並呼叫printf將之印出,以驗證你的轉換是否正確。

More Related