C Program Design Data Types

76
C Program Design Data Types 主主主 主主主

description

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. - PowerPoint PPT Presentation

Transcript of C Program Design Data Types

Page 1: C Program Design Data Types

C Program DesignData Types

主講人:虞台文

Page 2: C Program Design Data Types

Content Memory Concept Number Systems Basic Data Types

– int– char– float– Double

Data-Type Modifiers Type Conversions

Page 3: C Program Design Data Types

C Program DesignData Types

Memory Concept

Page 4: C Program Design Data Types

Computer Architecture

ALUALU

ControlControl

CPU

InputInput OutputOutput

MemoryMemory

InputDevice

OutputDevice

MemoryMemory

Page 5: C Program Design Data Types

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/10/1

0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1

0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1 0/10/1

Page 6: C Program Design Data Types

C Program DesignData Types

Number Systems

Page 7: C Program Design Data Types

Memory Space

00000000

00000001

00000002

00000003

00000004

00000005

00000006

00000007

00000008

FFFFFFFB

FFFFFFFC

FFFFFFFD

FFFFFFFE

FFFFFFFF

address

OS

mail

Word

HelloWorld

System Area

User Area

Page 8: C Program Design Data Types

Number Systems

Binary (0-1)– bn1bn2…b2b1b0

Octal (0-7)– on1on2…o2o1o0

Decimal (0-9)– dn1dn2…d2d1d0

Hexadecimal (0-9,A-F)– hn1hn2…h2h1h0

1

0

2n

kk

k

value b

1

0

8n

kk

k

value o

1

0

10n

kk

k

value d

1

0

16n

kk

k

value h

Examples:3 2 1 0

2 101011 1 2 0 2 1 2 1 2 11

3 2 1 08 103213 3 8 2 8 1 8 3 8 1675

2 1 010 10813 8 10 1 10 3 10 813

2 1 016 102 12 16 2 16 10 16 3114C A

Page 9: C Program Design Data Types

Number System Conversion

Binary (0-1)– bn1bn2…b2b1b0

Octal (0-7)– on1on2…o2o1o0

Decimal (0-9)– dn1dn2…d2d1d0

Hexadecimal (0-9,A-F)– hn1hn2…h2h1h0

1

0

2n

kk

k

value b

1

0

8n

kk

k

value o

1

0

10n

kk

k

value d

1

0

16n

kk

k

value h

Examples:3 2 1 0

2 101011 1 2 0 2 1 2 1 2 11

3 2 1 08 103213 3 8 2 8 1 8 3 8 1675

2 1 010 10813 8 10 1 10 3 10 813

2 1 016 102 12 16 2 16 10 16 3114C A

Page 10: C Program Design Data Types

Number System Conversion

Decimal Binary Octal Hexadecimal

000000010010001101000101

0111

1001

0110

1000

101010111100110111101111

012345

7

9

6

8

101112131415

012345

7

11

6

10

121314151617

012345

7

9

6

8

ABCDEF

Page 11: C Program Design Data Types

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);}

#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);}

Page 12: C Program Design Data Types

Data Coding

0 1 1 1 0 0 1 1

11510

7 = 01112 3 = 00112

= 011100112

= 011100112

= 011100112

int totalMoney = 115;int motorState = 115;int girl_boy = 115;

int totalMoney = 115;int motorState = 115;int girl_boy = 115;

Page 13: C Program Design Data Types

練習1. 輸入一介於 0-255 之十進位數字用於表示八台馬達之狀態 ( 如

前投影片所示 ) ,利用你目前所學過之 C 敘述撰寫一程式,輸出各台馬達之狀態。例:

Page 14: C Program Design Data Types

練習2. 輸入一介於 0-255 之十進位數字用於表示男女孩數 ( 如前投影

片所示 ) ,利用你目前所學過之 C 敘述撰寫一程式,輸出男孩與女孩數。例:

Page 15: C Program Design Data Types

C Program DesignData Types

Basic Date Types

Page 16: C Program Design Data Types

Basic Data Types

chara single byte, capable of holding one character in the local character set

intan 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.

Page 17: C Program Design Data Types

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 *));}

#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 *));}

Page 18: C Program Design Data Types

int Signed Integer

The size of int is dependent on machine It is usually the most efficient data type of a machi

ne, 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 (-2147483647 - 1) /* minimum (signed) int value */#define INT_MAX 2147483647 /* maximum (signed) int value */

#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */#define INT_MAX 2147483647 /* maximum (signed) int value */

Page 19: C Program Design Data Types

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);}

#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);}

Page 20: C Program Design Data Types

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)

ASCII

用於表示一個 Byte 足夠表示之整數

Overflow 由程式設計師負責

Page 21: C Program Design Data Types

Integer ConstantsASCII

#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);}

#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);}

Page 22: C Program Design Data Types

練習1. 預測以下程式中哪些敘述編譯時會產生錯誤 (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';}

#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';}

Page 23: C Program Design Data Types

char Signed Character

The size of char is 8 bits (1 byte) Although it is named character, it is in fact an integ

er 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

#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

CHAR_MIN (-128)INT_MAX 127

Page 24: C Program Design Data Types

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)

CHAR_MIN (-128)INT_MAX 127

ASCII

Page 25: C Program Design Data Types

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)

ASCII

用於表示一個 Byte 足夠表示之整數

Overflow 由程式設計師負責

Page 26: C Program Design Data Types

Character Constants

 \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

Some Escape Sequences

Page 27: C Program Design Data Types

範例: 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);}

#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);}

Page 28: C Program Design Data Types

範例: Escape Sequences

#include <stdio.h>

main(){ printf("\x6d\x6f\x64\x65\x6d\n");}

#include <stdio.h>

main(){ printf("\x6d\x6f\x64\x65\x6d\n");}

ASCII

Page 29: C Program Design Data Types

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形成之陣列。

Page 30: C Program Design Data Types

範例: 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);}

#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);}

以下程式可以通過編譯,但結果卻與預期不同

Page 31: C Program Design Data Types

範例: 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);}

#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);}

以下程式可以通過編譯,但結果卻與預期不同

Page 32: C Program Design Data Types

練習

#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);}

#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);}

1. 試找出產生是項執行結果之原因

Page 33: C Program Design Data Types

常用之字元輸出入函式 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 outp

ut (stdout) and advances the internal file position indicator to the next position.

Page 34: C Program Design Data Types

/* 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);}

/* 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);}

範例:字元輸出入函式

Page 35: C Program Design Data Types

/* 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);}

/* 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);}

範例:字元輸出入函式

Page 36: C Program Design Data Types

陣列 (Arrays)

Array is a data structure that stores contiguous data elements of the same type.

Examples:int score[50];char address[50];double distance[50];

score

address

distance

200

byte

s50

byte

s400

byte

s

Page 37: C Program Design Data Types

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

score

address

distance

...

score[0]

score[1]

score[49]

Page 38: C Program Design Data Types

陣列 (Arrays)

score

address

distance

address[0]address[1]address[2]

address[49]

...

Examples:int score[50];char address[50];double distance[50];

Page 39: C Program Design Data Types

陣列 (Arrays)

score

address

distance ...

distance[0]

distance[49]

Examples:int score[50];char address[50];double distance[50];

Page 40: C Program Design Data Types

陣列使用注意事項 陣列之索引 (index) 由 0開始

– 一陣列若含 n元素,其索引由 0至 n-1

C Compiler 對陣列索引不做 out of range 檢查– 易產生程式錯誤,甚或系統失敗– 寫程式時程式設計師應保證陣列索引不超出範圍

Page 41: C Program Design Data Types

範例: 輸入若干位學生成績將之儲存於一整數陣列中,並求算平均成績。

#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);}

#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);}

Page 42: C Program Design Data Types

練習: 1. 修改此範例,使之於輸入所有成績完畢後,亦能將每位學生給予 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);}

#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);}

Page 43: C Program Design Data Types

範例:陣列之定義#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]);}

#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]);}

Page 44: C Program Design Data Types

#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]);}

#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 執行結果

Page 45: C Program Design Data Types

#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]);}

#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 執行結果

對未定義初值之陣列元素值勿做臆測對未定義初值之陣列元素值勿做臆測

Page 46: C Program Design Data Types

字串 (String)

C 語言沒有定義字串資料型態 C 語言之字串係以零 (NUL) 作為結尾之字元陣列 (char array) 表示

例 :

char str[]="hello\n";

h (68)

e (65)

l (6C)

l (6C)

o (6F)

\n (0A)

\0 (00)

str str[0]

str[1]

str[2]

str[3]

str[4]

str[5]

str[6]

sizeof(str) = 7

Page 47: C Program Design Data Types

範例:#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}

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

輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。

Page 48: C Program Design Data Types

範例:#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}

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

輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。

Page 49: C Program Design Data Types

範例:#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}

#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;

Page 50: C Program Design Data Types

練習:1. 製作一 C 程式,從標準輸入裝置成功的讀取一十進

制整數字串 ( 可能含正負號 ) , 並將之儲存於一字元陣列中。

2. 將上題儲存於陣列中之字串轉換成整數,並呼叫 printf將之印出,以驗證你的轉換是否正確。

Page 51: C Program Design Data Types

Float and Double

IEEE 754

Page 52: C Program Design Data Types

Header Files

<limits.h>

and

<float.h>

Page 53: C Program Design Data Types

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)

Page 54: C Program Design Data Types

範例:#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 ));}

#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 ));}

畢氏定理 (Pythagorean theorem )

a2 + b2 = c2

Page 55: C Program Design Data Types

範例:#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 ));}

#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 ));}

畢氏定理 (Pythagorean theorem )

a2 + b2 = c2

Page 56: C Program Design Data Types

練習:1. 參考 http://zh.wikibooks.org/wiki/%E4%B8%89%E8%A7%92%E5%87%BD%E6

%95%B8製作一 C 程式,列印出 sin, cos, tan 表格。

2. 求二元一次方程式 (ax2 + bx + c = 0) 之解,需考慮有兩組實解、有兩組虛解及僅單一解之情況。

Page 57: C Program Design Data Types

C Program DesignData Types

Data-Type Modifiers

Page 58: C Program Design Data Types

Basic Data Types

chara single byte, capable of holding one character in the local character set

intan integer, typically reflecting the natural size of integers on the host machine

float single-precision floating point

double double-precision floating point

Page 59: C Program Design Data Types

Modifiers

short long signed unsigned

Page 60: C Program Design Data Types

Data Types in Real World

typebytes

bits range

char 1 8 128 127

unsigned char 1 8 0 255

short int 2 16 32,768 32,767

unsigned short int 2 16 0 65,535

int 4 32 -2,147,483,648 +2,147,483,647

unsigned int 4 32 0 4,294,967,295

long int 4 32 -2,147,483,648 +2,147,483,647

unsigned long int 4 32 0 4,294,967,295

float 4 32 single-precision floating point

double 8 64 double-precision floating point

long double 8 64 extended-precision floating point

Page 61: C Program Design Data Types

Data Types in Real World

typebytes

bits range

char 1 8 128 127

unsigned char 1 8 0 255

short int 2 16 32,768 32,767

unsigned short int 2 16 0 65,535

int 4 32 -2,147,483,648 +2,147,483,647

unsigned int 4 32 0 4,294,967,295

long int 4 32 -2,147,483,648 +2,147,483,647

unsigned long int 4 32 0 4,294,967,295

float 4 32 single-precision floating point

double 8 64 double-precision floating point

long double 8 64 extended-precision floating point

type bytes

bits range

char 1 8 128 127

unsigned char 1 8 0 255

short int 2 16 32,768 32,767

unsigned short int 2 16 0 65,535

int 4 32 -2,147,483,648 +2,147,483,647

unsigned int 4 32 0 4,294,967,295

long int 4 32 -2,147,483,648 +2,147,483,647

unsigned long int 4 32 0 4,294,967,295

float 4 32 single-precision floating point

double 8 64 double-precision floating point

long double 8 64 extended-precision floating point

Page 62: C Program Design Data Types

On Integer Data Types

Page 63: C Program Design Data Types

範例 : 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; }

#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; }

Page 64: C Program Design Data Types

C Program DesignData Types

Type

Conversions

Page 65: C Program Design Data Types

Type Hierarchies type byte

sbits range

char 1 8 128 127

unsigned char 1 8 0 255

short int 2 16 32,768 32,767

unsigned short int 2 16 0 65,535

int 4 32 -2,147,483,648 +2,147,483,647

unsigned int 4 32 0 4,294,967,295

long int 4 32 -2,147,483,648 +2,147,483,647

unsigned long int 4 32 0 4,294,967,295

float 4 32 single-precision floating point

double 8 64 double-precision floating point

long double 8 64 extended-precision floating pointwider

narrow

Page 66: C Program Design Data Types

Type Conversions

Implicit 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

Page 67: C Program Design Data Types

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 conve

rted to double – Otherwise, if either operand is float the other is convert

ed to float – Otherwise, convert char and short to int – Then, if an operand is long convert the other to long.

Page 68: C Program Design Data Types

範例 :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

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

Page 69: C Program Design Data Types

練習 :Implicit Type Conversion

1. 預測右方程式將產生之輸出為何?編譯執行後驗證你的預測是否正確?

2. 說明 C 編譯器在編譯右方程式時,將對各 assignment 做哪些 implicit type conversions ?

Page 70: C Program Design Data Types

Explicit Type Conversion: Casting

(type name) expression

Page 71: C Program Design Data Types

範例 :Type Casting

(type name) expression

Page 72: C Program Design Data Types

範例 :Type Casting

(type name) expression

Page 73: C Program Design Data Types

範例 :Type Casting

(type name) expression

Page 74: C Program Design Data Types

範例 :Type Casting

(type name) expression

Page 75: C Program Design Data Types

範例 :Type Casting

(type name) expression

Page 76: C Program Design Data Types

More on Type Casting

(type name) expression

The cast operator has the same high precedence as other unary operators.