查找美分对应的英文单词
1、用两个数组
1 #include<stdio.h> 2 3 int amount[] = { 1,5,10,25,50 }; 4 char* name[] = { "penny","mickel","dimme","quarter","half-dollar" }; 5 6 int search(int key, int a[], int len); 7 int main(void) 8 { 9 int k = 10; //需要找的数 10 int r = search(k, amount, sizeof(amount) / sizeof(amount[0])); 11 12 if (r != -1) 13 { 14 printf("%s ", name[r]); 15 } 16 return 0; 17 } 18 19 int search(int key, int a[], int len) 20 { 21 int ret = -1; 22 for (int i = 0; i < len; i++) 23 { 24 if (key == a[i]) 25 { 26 ret = i; 27 break; 28 } 29 } 30 return ret; 31 }
2、结构体
1 #include<stdio.h> 2 3 struct 4 { 5 int amount; 6 char* name; 7 } coins[] = { 8 {1,"penny"}, 9 {5,"nikel"}, 10 {10,"dime"}, 11 {25,"quarter"}, 12 {50,"half-dollar"} 13 }; 14 15 int main(void) 16 { 17 int k = 10; //需要找的数 18 for (int i = 0; i < sizeof(coins) / sizeof(coins[0]); i++) 19 { 20 if (k == coins[i].amount) 21 { 22 printf("%s ", coins[i].name); 23 } 24 }
return 0; 25 }