题目
美元硬币从小到大分为1美分(penny)5美分(nickel)10美分(dime)25美分(quarter)和50美分(half-dollar),写一个程序实现当给出一个数字面额可以输出相对应的名字。
代码一
用两个数组进行,一个数组表示面额,另一个表示名字,然后通过对应关系进行输出。
#include<stdio.h>
int amount[] = {1,5,10,25,50};
char *name[] = {"penny","nickel","dime","quarter","half-dollar"};
int search(int key, int a[], int len){
int ret = -1;
for(int i=0; i<len; i++)
{
if(key == a[i])
{
ret = i;
break;
}
}
return ret;
}
int main()
{
int k = 8;
int r = search(k, amount, sizeof(amount)/sizeof(amount[0]));
if(r>-1)
{
printf("%s\n", name[r]);
} else
{
printf("输入错误,请重新输入");
}
}
运行结果
代码二
构造结构体,把面额和名字放在一个数组中
#include<stdio.h>
int amount[] = {1,5,10,25,50};
char *name[] = {"penny","nickel","dime","quarter","half-dollar"};
struct{//构造结构体
int amount;
char *name;
} coins[] = {
{1, "penny"},
{5, "nickel"},
{10, "dime"},
{25, "quarter"},
{50, "half-dollar"}
};//;不能省!!!!!
int main()
{
int k = 10;
for(int i=0; i<sizeof(coins)/sizeof(coins[0]); i++)
{
if(k == coins[i].amount){
printf("%s\n", coins[i].name);
break;
}
}
}
运行结果