C语言找零问题

1.找零问题

    钱的面值有1毛,5毛,1块,5块,10块,20块,50块,100块,大于100的就不算找零了,用贪心算法来找零,使得每次找零的钱的张数和最小

2.代码:

#include 
#include 



void change(double money, double pay)
{
	
	int count[7] = {0}; //个个面值钱的张数
	
	double change= money - pay;//找零的钱
	
	while (change > 0) {

	
	if (change >= 500) {
		change = change - 500;		
		count[6] ++;

	}
	if (change>=200&&change<500)
	{
		change = change -200;
		count[5] ++;
	}
	if (change >= 100 && change < 200)
	{
		change = change -  100;
		count[4] ++;
	}
	if (change >= 50 && change < 100)
	{
		change = change -  50;
		count[3] ++;
	}
	if (change >= 10 && change < 50)
	{
		change = change - 10;
		count[2] ++;
	}
	if (change >= 5&&change < 10)
	{
		change = change - 5;
		count[1]++;
	}
	if (change < 5)
	{
		change = change - 1;
		count[0]++;
	}

	}
	

        //打印数组
	for (int i = 0; i < 7; i++)
	{
		printf("%d\t", count[i]);
	}
	printf("\n");
}

int main()
{
	printf("找零:找零1毛,5毛,1块,5块,10块,20块,50块的零钱,大于100不算零钱了\n");

	double money = 100;
	double pay = 14.6;
	printf("给了%.1f,花费%.1f\n", money, pay);
	printf("输出相应零钱的张数:\n");
	money = money * 10;				//因为double的精度不到0.1所以把钱面值扩大10倍
	pay = pay * 10;
	printf("0.1	0.5	1	5	10	20	50 \n");
	change(money, pay);
	system("pause");
	return 0;

}

3.运行结果:

C语言找零问题_第1张图片

你可能感兴趣的:(编程)