SRM 219 Div II Level One: WaiterTipping,小心约分

题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=12609&rd=15503


这题目看上去so easy, 但写的时候要特别小心,如果直接按照公式算,没有加下面这一句的话:

	if (total + total * taxPercent / 100 + (tip + 1) * total / 100 <= money) {
			++tip;
		}

那么因为公式涉及向下约分的运算,那么所得到的tip的值可能是比最大值小1的值。一定要加上这一句进行判定。


当然还有一种解法就是用循环,tip值从money 到1,当满足公式时,则此时tip的值就是解,这种方法效率低, 

但不容易出错!


代码如下:

#include <iostream>

using namespace std;

class WaiterTipping
{
public:
	int maxPercent(int total, int taxPercent, int money);
};

int WaiterTipping::maxPercent(int total, int taxPercent, int money)
{
	int res = money - ( total + total * taxPercent / 100 );
	int tip;
	if (res >= 0) {
		tip = res * 100 / total;

		/* 关键不能少,上面得到的tip可能不是最大值,而是比最大值小1的值 */
		if (total + total * taxPercent / 100 + (tip + 1) * total / 100 <= money) {
			++tip;
		}

		return tip;
	}
	return -1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值