Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Program Design Data Types

Similar presentations


Presentation on theme: "C Program Design Data Types"— Presentation transcript:

1 C Program Design Data Types
主講人:虞台文

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

3 C Program Design Data Types
Memory Concept

4 Computer Architecture
ALU Control CPU Input Output Memory Device Memory

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

6 Memory Space OS System Area mail Word User Area HelloWorld address
FFFFFFFB FFFFFFFC FFFFFFFD FFFFFFFE FFFFFFFF OS System Area mail User Area Word HelloWorld

7 C Program Design Data Types
Number Systems

8 Number Systems Binary (0-1) Octal (0-7) Decimal (0-9)
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 Examples:

9 Number System Conversion
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 Examples:

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

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 Data Coding int totalMoney = 115; int motorState = 115; int girl_boy = 115; 11510 = = 1 = 7 = 01112 3 = 00112

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

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

15 C Program Design Data Types
Basic Date Types

16 Basic Data Types char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point 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> #define INT_MIN ( ) /* minimum (signed) int value */ #define INT_MAX /* maximum (signed) int value */

19 int  Signed Integer INT_MIN (-2147483647 - 1) INT_MAX 2147483647
#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 Integer Constants ASCII
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 Integer Constants ASCII #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" }

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= ; v4 = ; v5 = 0x100; v6 = '\x100'; v7 = 0377; v8 = '\377'; v9 = 0477; v10 = '\477'; }

23 char  Signed Character
CHAR_MIN (-128) CHAR_MAX 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 /* maximum signed char value */ // #define CHAR_MIN SCHAR_MIN #define CHAR_MAX SCHAR_MAX

24 char  Signed Character
CHAR_MIN (-128) char_MAX 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 Character Constants ASCII
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 \a alert (bell) character \\
 \\   backslash  \b  backspace  \?  question mark  \f  formfeed  \'  single quote  \n  newline  \"   double quote  \r  carriage return  \000  octal number  \t  horizontal tab  \xhh  hexadecimal number   \v  vertical tab

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" }

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

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

30 範例:char vs. 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 範例:char vs. 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 ); int putchar ( int character );
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 陣列(Arrays) 記 憶 體 Examples:
score Array is a data structure that stores contiguous data elements of the same type. 200 bytes 50 400 address distance Examples: int score[50]; char address[50]; double distance[50];

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

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

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

40 陣列使用注意事項 陣列之索引(index)由0開始 C Compiler對陣列索引不做out of range檢查
一陣列若含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 範例:陣列之定義 Debugging Mode執行結果 #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 範例:陣列之定義 對未定義初值之陣列元素值勿做預測 Release Mode執行結果 #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 字串(String) char str[]="hello\n"; C語言沒有定義字串資料型態
C語言之字串係以零(NUL)作為結尾之字元陣列(char array)表示 例: h (68) e (65) l (6C) o (6F) \n (0A) \0 (00) 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將之印出,以驗證你的轉換是否正確。

51 Float and Double IEEE 754

52 Header Files <limits.h> and <float.h>

53 Floating Point Constants
Floating point constants contain a decimal point or exponent. By default they are double. 123.4 (double) 1e-2 (double) 124.4f (float) 1e-2f (float)

54 範例: a2 + b2 = c2 畢氏定理(Pythagorean theorem ) #include <stdio.h>
#include <math.h> main() { double a, b; printf("Enter two legs a and b of a right triangle:"); scanf("%lf%lf",&a,&b); printf("The hypotenuse c of the triangle is %10.5lf\n", sqrt(a * a + b * b )); }

55 範例: a2 + b2 = c2 畢氏定理(Pythagorean theorem ) #include <stdio.h>
#include <math.h> main() { double a, b; printf("Enter two legs a and b of a right triangle:"); scanf("%lf%lf",&a,&b); printf("The hypotenuse c of the triangle is %10.5lf\n", sqrt(a * a + b * b )); }

56 練習: 參考 cos, tan表格。 求二元一次方程式(ax2 + bx + c = 0)之解,需考慮有兩組實解、有兩組虛解及僅單一解之情況。

57 C Program Design Data Types
Data-Type Modifiers

58 Basic Data Types char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point

59 Modifiers short long signed unsigned

60 Data Types in Real World
bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point

61 Data Types in Real World
bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point type bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point

62 On Integer Data Types

63 範例: Sizes of C Data Types
#include <stdio.h> /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; }

64 C Program Design Data Types
Type Conversions

65 Type Hierarchies narrow wider single-precision floating point
bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point wider narrow

66 Type Conversions Implicit type conversion Explicit type conversion
also known as coercion automatically done by the compiler when type mismatch on operands narrower type  wider type Explicit type conversion also known as casting done by programmer

67 Implicit Type Conversion
General rules for binary operators (+-*/%etc) If either operand is long double the other is converted to long double. Otherwise, if either operand is double the other is converted to double Otherwise, if either operand is float the other is converted to float Otherwise, convert char and short to int Then, if an operand is long convert the other to long.

68 範例:Implicit Type Conversion
int a; unsigned long b; float f, g; double d; g = a + f; // a transforms to float d = a + b; // a and b transform to unsigned long, adding // is produced in unsigned long domain and then // the result type unsigned long is transformed // to double

69 練習:Implicit Type Conversion
預測右方程式將產生之輸出為何?編譯執行後驗證你的預測是否正確? 說明C編譯器在編譯右方程式時,將對各assignment做哪些implicit type conversions ?

70 Explicit Type Conversion: Casting
(type name) expression

71 (type name) expression
範例:Type Casting

72 (type name) expression
範例:Type Casting

73 (type name) expression
範例:Type Casting

74 (type name) expression
範例:Type Casting

75 (type name) expression
範例:Type Casting

76 More on Type Casting (type name) expression
The cast operator has the same high precedence as other unary operators.


Download ppt "C Program Design Data Types"

Similar presentations


Ads by Google