3 回答

TA貢獻1856條經驗 獲得超11個贊
一、對枚舉型的變量賦值。
實例將枚舉類型的賦值與基本數據類型的賦值進行了對比:
方法1:先聲明變量,再對變量賦值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include<stdio.h> /* 定義枚舉類型 */ enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }; void main() { /* 使用基本數據類型聲明變量,然后對變量賦值 */ int x, y, z; x = 10; y = 20; z = 30; /* 使用枚舉類型聲明變量,再對枚舉型變量賦值 */ enum DAY yesterday, today, tomorrow; yesterday = MON; today = TUE; tomorrow = WED; printf("%d %d %d \n", yesterday, today, tomorrow); } |
方法2:聲明變量的同時賦初值
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> /* 定義枚舉類型 */ enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }; void main() { /* 使用基本數據類型聲明變量同時對變量賦初值 */ int x=10, y=20, z=30; /* 使用枚舉類型聲明變量同時對枚舉型變量賦初值 */ enum DAY yesterday = MON, today = TUE, tomorrow = WED; printf("%d %d %d \n", yesterday, today, tomorrow); } |
方法3:定義類型的同時聲明變量,然后對變量賦值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> /* 定義枚舉類型,同時聲明該類型的三個變量,它們都為全局變量 */ enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } yesterday, today, tomorrow; /* 定義三個具有基本數據類型的變量,它們都為全局變量 */ int x, y, z; void main() { /* 對基本數據類型的變量賦值 */ x = 10; y = 20; z = 30; /* 對枚舉型的變量賦值 */ yesterday = MON; today = TUE; tomorrow = WED; printf("%d %d %d \n", x, y, z); //輸出:10 20 30 printf("%d %d %d \n", yesterday, today, tomorrow); //輸出:1 2 3 } |
方法4:類型定義,變量聲明,賦初值同時進行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> /* 定義枚舉類型,同時聲明該類型的三個變量,并賦初值。它們都為全局變量 */ enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } yesterday = MON, today = TUE, tomorrow = WED; /* 定義三個具有基本數據類型的變量,并賦初值。它們都為全局變量 */ int x = 10, y = 20, z = 30; void main() { printf("%d %d %d \n", x, y, z); //輸出:10 20 30 printf("%d %d %d \n", yesterday, today, tomorrow); //輸出:1 2 3 } |
2、對枚舉型的變量賦整數值時,需要進行類型轉換。
1 2 3 4 5 6 7 8 9 10 11 | #include <stdio.h> enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }; void main() { enum DAY yesterday, today, tomorrow; yesterday = TUE; today = (enum DAY) (yesterday + 1); //類型轉換 tomorrow = (enum DAY) 30; //類型轉換 //tomorrow = 3; //錯誤 printf("%d %d %d \n", yesterday, today, tomorrow); //輸出:2 3 30 } |
3、使用枚舉型變量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include<stdio.h> enum { BELL = '\a', BACKSPACE = '\b', HTAB = '\t', RETURN = '\r', NEWLINE = '\n', VTAB = '\v', SPACE = ' ' }; enum BOOLEAN { FALSE = 0, TRUE } match_flag; void main() { int index = 0; int count_of_letter = 0; int count_of_space = 0; char str[] = "I'm Ely efod"; match_flag = FALSE; for(; str[index] != '\0'; index++) if( SPACE != str[index] ) count_of_letter++; else { match_flag = (enum BOOLEAN) 1; count_of_space++; } printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE); printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN); } |
- 3 回答
- 0 關注
- 600 瀏覽
添加回答
舉報