‘壹’ c语言 购物找零
#include<stdio.h>
int main()
{
float m,n,p;
scanf("%f%f%f",&m,&n,&p);
if(m>=n*p)
printf("找零:%.2f",m-n*p);
if(m<n*p)
printf("Failed");
return 0;
}
‘贰’ C语言,贪心算法,货币找零问题
贪心算法找零就是现实中从最大面额开始找的思路。不代表是最优解,只是算法之一。
由于面额输入顺序不定,我先对输入的面额进行降序排序。
下面代码:
#include <stdio.h>
#include <malloc.h>
int main()
{
int i,j,m,n,*ns=NULL,*cn=NULL,sum=0;
printf("请输入总金额m及零钱种类n:"),scanf("%d",&m),scanf("%d",&n);
printf("请分别输入%d种零钱的面额: ",n);
if(!(ns=(int *)malloc(sizeof(int)*n))) return 1;
if(!(cn=(int *)malloc(sizeof(int)*n))) return 1;
for(i=0;i<n;i++) scanf("%d",&ns[i]);
//------------考虑输入面额顺序不定,先对面额进行降序排列(如按照降序输入,该段可删除)
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(ns[j]>ns[i]) ns[j]^=ns[i],ns[i]^=ns[j],ns[j]^=ns[i];
//-------------------------------------------------------------------
for(i=0;i<n;i++)//贪心算法,从最大面额开始
if(m>=ns[i])
cn[i]=m/ns[i],m=m%ns[i],sum+=cn[i],printf("%d元%d张 ",ns[i],cn[i]);
printf(" 最少使用零钱%d张 ",sum);
return 0;
}
‘叁’ C语言实收金额找零代码怎么写
#include<stdio.h>
voidmain()
{
doubleprice,money=0;
intnum;
printf("请输入方便面的价格和购买的数量:");
scanf("%lf%d",&price,&num);
money+=price*num;
printf("请输入作业本的价格和购买的数量:");
scanf("%lf%d",&price,&num);
money+=price*num;
printf("请输入圆珠笔的价格和购买的数量:");
scanf("%lf%d",&price,&num);
money+=price*num;
printf("应付金额:%.2lf ",money);
printf("实收金额:");
{
doublemoney1;
scanf("%lf",&money1);
printf("找零:%.2lf ",money1-money);
}
}
‘肆’ c语言找零钱问题
double iChange=0;
double taget=0.72;
double Money[5] = { 0.5, 0.1, 0.05, 0.02, 0.01};
double ArrChange[100];
for语句将ArrChange置零;
int CountCoin=0;
while(iChange != taget )
{
for(int i = 0 ; i < 5 ; i ++)
{
if(iChange + Money[i] > taget)continue;
else
{
iChange += Money[i];
ArrChange[CountCoin] = Money[i];
CountCoin++;
}
}
}
//基本是这么个思路,如果一点也不思考对你没好处,原理就是找多了就换小的,尽量选大的钱
‘伍’ 用C语言编写找零钱问题,谢谢!!
//用递归, C++下调试
#include <iostream>
using namespace std;
void compute_coins(int coin_value,int& number,int& amount_left){
if(amount_left >= coin_value)
compute_coins(coin_value, ++number, amount_left -= coin_value);
else{
cout << coin_value << ":" << number << endl;
number = 0;
switch(coin_value){
case 25:
compute_coins(10, number, amount_left);
break;
case 10:
compute_coins(5, number, amount_left);
break;
case 5:
compute_coins(1, number, amount_left);
break;
}
}
}
int main()
{
int n;
cin >> n;
int number = 0;
compute_coins(25, number, n);
}
//下面是C语言的,更直观,不需要引用
#include <stdio.h>
void compute_coins(int coin_value,int number,int amount_left){
if(amount_left >= coin_value)
compute_coins(coin_value, number+1, amount_left-coin_value);
else{
printf("%d : %d\n", coin_value, number);
switch(coin_value){
case 25:
compute_coins(10, 0, amount_left);
break;
case 10:
compute_coins(5, 0, amount_left);
break;
case 5:
compute_coins(1, 0, amount_left);
break;
}
}
}
int main()
{
int n;
printf("input amount:");
scanf("%d", &n);
compute_coins(25, 0, n);
}