列舉型別簡單例子
阿新 • • 發佈:2019-01-31
//列舉型別例子
#include<stdio.h>
int main()
{
enum Color {red ,yellow,blue,white,black };//宣告列舉型別enum Color
int i, j, k, pri;//定義列舉變數
int n, loop;
n = 0;
for (i = red; i <= black;i++)//外迴圈使i的值從red 變到black
for (j = red; j <= black; j++)//中迴圈使j的值從red變到black
if (i != j)//如果兩球不同色
{
for (k = red; k <= black; k++)//內迴圈使k的值從red變到black
if (i != k && j != k)//如果三球不同色
{
n = n + 1; //符合條件的次數加1
printf("%-4d\n", n);//輸出當前是第幾個符合條件的組合
for (loop = 1; loop <= 3; loop++)//先後對三個球分別處理
{
switch (loop) //loop的值從1變到3
{
case 1: pri = i; break;//loop的值為1時,把第1個球的顏色賦給pri;
case 2: pri = j; break;//loop的值為2時,把第2個球的顏色賦給pri;
case 3: pri = k; break;//loop的值為3時,把第3個球的顏色賦給pri;
default:break;
}
switch (pri)//根據球的顏色輸出相應的文字
{
case red:printf("%-10s", "red"); break;//pri的值等於列舉常亮red時輸出“red”;
case yellow:printf("%-10s", "yellow"); break;//pri的值等於列舉常亮yellow時輸出“yellow”;
case blue:printf("%-10s", "blue"); break;//pri的值等於列舉常亮blue時輸出“blue”;
case white:printf("%-10s", "white"); break;//pri的值等於列舉常亮white時輸出“white”;
case black:printf("%-10s", "black"); break;//pri的值等於列舉常亮black時輸出“black”;
default:break;
}
}
printf("\n");
}
}
printf("\ntotle:%5d\n", n);
return 0;
}
#include<stdio.h>
int main()
{
enum Color {red ,yellow,blue,white,black };//宣告列舉型別enum Color
int i, j, k, pri;//定義列舉變數
int n, loop;
n = 0;
for (i = red; i <= black;i++)//外迴圈使i的值從red 變到black
for (j = red; j <= black; j++)//中迴圈使j的值從red變到black
if (i != j)//如果兩球不同色
{
for (k = red; k <= black; k++)//內迴圈使k的值從red變到black
if (i != k && j != k)//如果三球不同色
{
n = n + 1; //符合條件的次數加1
printf("%-4d\n", n);//輸出當前是第幾個符合條件的組合
for (loop = 1; loop <= 3; loop++)//先後對三個球分別處理
{
switch (loop) //loop的值從1變到3
{
case 1: pri = i; break;//loop的值為1時,把第1個球的顏色賦給pri;
case 2: pri = j; break;//loop的值為2時,把第2個球的顏色賦給pri;
case 3: pri = k; break;//loop的值為3時,把第3個球的顏色賦給pri;
default:break;
}
switch (pri)//根據球的顏色輸出相應的文字
{
case red:printf("%-10s", "red"); break;//pri的值等於列舉常亮red時輸出“red”;
case yellow:printf("%-10s", "yellow"); break;//pri的值等於列舉常亮yellow時輸出“yellow”;
case blue:printf("%-10s", "blue"); break;//pri的值等於列舉常亮blue時輸出“blue”;
case white:printf("%-10s", "white"); break;//pri的值等於列舉常亮white時輸出“white”;
case black:printf("%-10s", "black"); break;//pri的值等於列舉常亮black時輸出“black”;
default:break;
}
}
printf("\n");
}
}
printf("\ntotle:%5d\n", n);
return 0;
}