【PAT B1020】月饼 (C语言)

在这里插入图片描述
注意一下,当需求大于所有库存的情况

#include <stdio.h>
#define MAX_N 1000			/* 月饼最大种类数 */
int N;						/* 种类 */
float demand;				/* 需求量 */
typedef struct mooncake{
	float inventory;		/* 库存量 */
	float price;			/* 单价 */
}mooncake;
struct mooncake nmc[MAX_N];	/* N种月饼的信息 n moon cake */
void read_info();
void print_income();
int getMaxP();
/******* 读入月饼种类数,需求量,以及读入N中月饼的库存和总售价,并计算单价 ********/
void read_info(){
	int i;

	scanf("%d %f", &N, &demand);
	for(i = 0; i < N; ++i)
		scanf("%f", &nmc[i].inventory);
	for(i = 0; i < N; ++i){
		scanf("%f", &nmc[i].price);
		nmc[i].price /= nmc[i].inventory;
	}
}
/******************************** 计算收益 ****************************************/
void print_income(){
	float income = 0;					/* 收益 */
	int p_max;							/* 最大单价月饼的下标 */

	while(demand > 0){					/* 当需求量还没有满足 */
		p_max = getMaxP();				/* 找一个单价最大的月饼 */
		if(nmc[p_max].inventory == 0)	/* 所有的库存都满足不了需求 售空了 */
			break;
		else if(demand >= nmc[p_max].inventory){/* 当前月饼种类的库存不能满足需求 */
			income += nmc[p_max].inventory * nmc[p_max].price;
			demand -= nmc[p_max].inventory;
			nmc[p_max].inventory = 0;
		}else{							/* 需求小于库存 */
			income += demand * nmc[p_max].price;
			break;
		}
	}
	printf("%.2f", income);				/* 输出收益 */
}
/***************************** 找最大单价的月饼 ************************************/
int getMaxP(){
	int i, j;
	float p;

	p = j = 0;
	for(i = 0; i < N; ++i)
		if(nmc[i].inventory > 0 && nmc[i].price > p){
			p = nmc[i].price;
			j = i;
		}
	return j;				/* 返回最大单价的位置 */
}
int main(){
	read_info();			/* 读入信息 */
	print_income();			/* 输出收益 */
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值