现在的位置: 首页 > 综合 > 正文

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

2013年10月12日 ⁄ 综合 ⁄ 共 675字 ⁄ 字号 评论关闭

题目来源: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;
}

抱歉!评论已关闭.