用C语言编写自动售货机

2024-11-26 22:36:39
推荐回答(1个)
回答1:

#include

bool GetCharge(int Sum,int Money);
void Getsmalcharge(int Money,int *ChargeNum);
void main()
{
char state='N';
int Sum=0;
char Pro;
printf("\n********************************\n");
while(true)
{
state='N';
Sum=0;
while(state=='N'||state=='n')
{
printf("\n输入购买物品(a,b,c):");
scanf("%c",&Pro);
getchar();
switch(Pro)
{
case 'a':
Sum=Sum+1;
break;
case 'A':
Sum=Sum+1;
break;
case 'b':
Sum=Sum+5;
break;
case 'B':
Sum=Sum+5;
break;
case 'c':
Sum=Sum+10;
break;
case 'C':
Sum=Sum+10;
break;
default:
printf("\n输入物品有误!!!!\n");
break;
};
printf("\n是否完成(Y/N):");
scanf("%c",&state);
getchar();
}
int Money;
printf("\n购买总价为:%d",Sum);
bool st=false;
while(!st)
{
printf("\n输入金额:");
scanf("%d",&Money);
getchar();
st=GetCharge(Sum,Money);
};
printf("\n----------------购买结束------------\n");
printf("\n");
printf("\n");
printf("\n");
}
}
//----------------------------------------------------
bool GetCharge(int Sum,int Money)
{
int ChargeNum[4];
for(int i=0;i<4;i++)
{
ChargeNum[i]=0;
}
if(Sum>Money)
{
printf("\n金额不够,请重新输入.....");
return false;
}
else if(Sum==Money)
{
printf("\n余额为0");
return true;
}
else
{
int Result=Money-Sum;
Getsmalcharge(Result,ChargeNum);
printf("\n余额为%d元,应找零\n1 元%d张\n2 元%d张\n5 元%d张\n10元%d张\n",Result,ChargeNum[0],ChargeNum[1],ChargeNum[2],ChargeNum[3]);

}//end if
return true;
}
//------------------------------------
void Getsmalcharge(int Money,int *ChargeNum)
{
if(Money<0)
return;
int Sum=Money;
int charge[4]={1,2,5,10};
ChargeNum[3]=Sum/charge[3];
Sum=Sum%charge[3];
ChargeNum[2]=Sum/charge[2];
Sum=Sum%charge[2];
ChargeNum[1]=Sum/charge[1];
Sum=Sum%charge[1];
ChargeNum[0]=Sum/charge[0];
Sum=Sum%charge[0];
}