笔试题32——超市找零方案

题目描述:
在日常消费中,超市收营员在结算中经常遇到需要给顾客找零的情况。为了节省人力,编写一个程序,要求输入顾客应付金额和实付金额,系统给出合适的找零方案。
输入描述:
输入应付金额和实付金额
输出描述:
输出合适的找零方案(注意最后要输出一个分号,所有输出都是英文半角状态,余额保留一位小数)
输入:
26.5 50
输出:
23.5 20:1;1:3;0.5:1;

核心代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include  

using namespace std;

int main()
{
	//50,20,10,5,1,0.5
	float m, n;
	cin >> m >> n;
	if (m == n) {
		cout << "0.0" << endl;
	}
	if (m > n)
		return 0;
	float res = n - m;
	printf("%.1lf ", res); //输出余额
	
	int c50 = 0, c20 = 0, c10 = 0, c05 = 0, c01 = 0, c005 = 0; //分别记录所需零钱个数

	while (res >= 50) {
		c50++;
		res -= 50;
	}

	while (res >= 20) {
		c20++;
		res -= 20;
	}

	while (res >= 10) {
		c10++;
		res -= 10;
	}

	while (res >= 5) {
		c05++;
		res -= 5;
	}

	while (res >= 1) {
		c01++;
		res -= 1;
	}

	while (res >= 0.5) {
		c005++;
		res -= 0.5;
	}

	if (c50 != 0) {
		cout << "50:" << c50 << ";";
	}
	if (c20 != 0) {
		cout << "20:" << c20 << ";";
	}
	if (c10 != 0) {
		cout << "10:" << c10 << ";";
	}
	if (c05 != 0) {
		cout << "5:" << c05 << ";";
	}
	if (c01 != 0) {
		cout << "1:" << c01 << ";";
	}
	if (c005 != 0) {
		cout << "0.5:" << c005 << ";";
	}
	cout << endl;

	return 0;
}

你可能感兴趣的:(笔试题)