P1089 [NOIP 2004 提高组] 津津的储蓄计划
题目
题目描述
津津的零花钱一直都是自己管理。每个月的月初妈妈给津津 300 300 3 0 0 元钱,津津会预算这个月的花销,并且总能做到实际花销和预算的相同。
为了让津津学习如何储蓄,妈妈提出,津津可以随时把整百的钱存在她那里,到了年末她会加上 20 % 20\% 2 0 % 还给津津。因此津津制定了一个储蓄计划:每个月的月初,在得到妈妈给的零花钱后,如果她预计到这个月的月末手中还会有多于 100 100 1 0 0 元或恰好 100 100 1 0 0 元,她就会把整百的钱存在妈妈那里,剩余的钱留在自己手中。
例如 11 11 1 1 月初津津手中还有 83 83 8 3 元,妈妈给了津津 300 300 3 0 0 元。津津预计11 11 1 1 月的花销是 180 180 1 8 0 元,那么她就会在妈妈那里存 200 200 2 0 0 元,自己留下 183 183 1 8 3 元。到了 11 11 1 1 月月末,津津手中会剩下 3 3 3 元钱。
津津发现这个储蓄计划的主要风险是,存在妈妈那里的钱在年末之前不能取出。有可能在某个月的月初,津津手中的钱加上这个月妈妈给的钱,不够这个月的原定预算。如果出现这种情况,津津将不得不在这个月省吃俭用,压缩预算。
现在请你根据 2004 2004 2 0 0 4 年 1 1 1 月到 12 12 1 2 月每个月津津的预算,判断会不会出现这种情况。如果不会,计算到 2004 2004 2 0 0 4 年年末,妈妈将津津平常存的钱加上 20 % 20\% 2 0 % 还给津津之后,津津手中会有多少钱。
输入格式
12 12 1 2 行数据,每行包含一个小于 350 350 3 5 0 的非负整数,分别表示 1 1 1 月到 12 12 1 2 月津津的预算。
输出格式
一个整数。如果储蓄计划实施过程中出现某个月钱不够用的情况,输出 − X -X − X ,X X X 表示出现这种情况的第一个月;否则输出到 2004 2004 2 0 0 4 年年末津津手中会有多少钱。
注意,洛谷不需要进行文件输入输出,而是标准输入输出。
输入输出样例 #1
输入 #1
1 2 3 4 5 6 7 8 9 10 11 12 290 230 280 200 300 170 340 50 90 80 200 60
输出 #1
输入输出样例 #2
输入 #2
1 2 3 4 5 6 7 8 9 10 11 12 290 230 280 200 300 170 330 50 90 80 200 60
输出 #2
分析
我们可以直接套模拟,模拟每个月的操作即可。
解题
我们可以写出程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 #include <iostream> using namespace std;int main () { int MonthMoneys[12 ]; for (int z = 0 ; z <= 11 ; z++) { int MonthMoney = 0 ; cin >> MonthMoney; MonthMoneys[z] = MonthMoney; } int i = 0 ; int mother = 0 ; int LeftMoney = 0 ; for (int month = 0 ; month <= 11 ; month++) { int ThisMonthMoney = LeftMoney + 300 ; if (ThisMonthMoney >= MonthMoneys[month]) { ThisMonthMoney -= MonthMoneys[month]; mother += (ThisMonthMoney / 100 ) * 100 ; LeftMoney = ThisMonthMoney % 100 ; i++; if (i == 11 ) { int AllMoney = mother * 1.2 + LeftMoney; cout << AllMoney; } } else { cout << '-' << month + 1 ; break ; } } return 0 ; }
但是提交之后,只得了60分。QAQ
经过分析后,发现代码存在以下几个问题:
终止条件错误 :使用 if (i == 11) 来判断是否是最后一个月输出结果,但 i 变量的作用不明确,而且 i 的值实际上不会等于 11。因此最后一个月可能不会正确输出最终结果。
存款计算错误 :mother * 1.2 可能导致浮点数运算错误,建议改成 mother * 120 / 100 避免浮点误差。
cout << AllMoney; 需要放在循环外 。
更改后代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include <iostream> using namespace std;int main () { int MonthMoneys[12 ]; for (int z = 0 ; z <= 11 ; z++) { int MonthMoney = 0 ; cin >> MonthMoney; MonthMoneys[z] = MonthMoney; } int i = 0 ; int mother = 0 ; int LeftMoney = 0 ; for (int month = 0 ; month <= 11 ; month++) { int ThisMonthMoney = LeftMoney + 300 ; if (ThisMonthMoney >= MonthMoneys[month]) { ThisMonthMoney -= MonthMoneys[month]; mother += (ThisMonthMoney / 100 ) * 100 ; LeftMoney = ThisMonthMoney % 100 ; i++; } else { cout << '-' << month + 1 ; return 0 ; } } int AllMoney = mother * 120 / 100 + LeftMoney; cout << AllMoney; return 0 ; }
这一次就是 AC 代码了。