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

来源:互联网 发布:淘宝差评处理技巧 编辑:程序博客网 时间:2024/04/29 02:20

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