1037. 在霍格沃茨找零钱(20)

题目描述

如果你是哈利·波特迷,你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的:“十七个银西可(Sickle)兑一个加隆(Galleon),二十九个纳特(Knut)兑一个西可,很容易。”现在,给定哈利应付的价钱P和他实付的钱A,你的任务是写一个程序来计算他应该被找的零钱。

输入格式:

输入在1行中分别给出P和A,格式为“Galleon.Sickle.Knut”,其间用1个空格分隔。这里Galleon是[0, 107] 区间内的整数,Sickle是 [0, 17) 区间内的整数,Knut是[0, 29) 区间内的整数。

输出格式:

在一行中用与输入同样的格式输出哈利应该被找的零钱。如果他没带够钱,那么输出的应该是负数。

输入样例1:

10.16.27 14.1.28

输出样例1:

3.2.1

输入样例2:

14.1.28 10.16.27

输出样例2:

-3.2.1

提交代码

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
#include <cstdio>
#include <cmath>
// note: 'std::abs'
using namespace std;
int main()
{
int pGalleon, pSickle, pKnut;
int aGalleon, aSickle, aKnut;
int cGalleon, cSickle, cKnut;

scanf("%d.%d.%d ", &pGalleon, &pSickle, &pKnut);
scanf("%d.%d.%d", &aGalleon, &aSickle, &aKnut);

pSickle += pGalleon * 17;
pKnut += pSickle * 29;
aSickle += aGalleon * 17;
aKnut += aSickle * 29;
// calculate the absolute value first
cKnut = abs(aKnut - pKnut);
cSickle = cKnut / 29;
cKnut = cKnut % 29;
cGalleon = cSickle / 17;
cSickle = cSickle % 17;
if (aKnut - pKnut < 0) {
printf("-");
}
printf("%d.%d.%d\n", cGalleon, cSickle, cKnut);

return 0;
}

个人思考

这里采用了一种非常粗暴的方法,先将所有的货币转化为最小单位 Knut,计算完了之后再换回去。

  1. abs 是命名空间 std 内的,在本地编译器里面没有加 std,没报错,提交后在 PAT 的编译系统里面报错了。要引起注意。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    a.cpp: In function 'int main()':
    a.cpp:22:47: error: 'abs' was not declared in this scope
    printf("%d.%d.%d\n", cGalleon, abs(cSickle), abs(cKnut));
    ^
    a.cpp:22:47: note: suggested alternative:
    In file included from a.cpp:2:0:
    /usr/include/c++/4.9/cmath:99:5: note: 'std::abs'
    abs(_Tp __x)
    ^
  2. 一开始的时候由于抄错数字,将 二十九个纳特(Knut)兑一个西可 误写为 19,一直拿不满分,但估计是巧合,有几个测试点能过。

  3. 在对不够钱还是要找零进行处理的时候,应该先对差价取绝对值之后再进行单位转换,而不是减完之后就地转换,输出的时候再取绝对值。