您的位置:首页 > 其它

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

2016-03-30 21:33 260 查看
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

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<math.h>
using namespace std;
int galleon2sickle=17;
int sickle2knut=29;//设置汇率
typedef struct
{
long knut;
long sickle;
long galleon;
}Money;//定义一个结构体更加附后逻辑思维
void  getLine(string s,Money &owe,Money &pay)
{
int index1=s.find_first_of(".",0);
int index2=s.find_first_of(".",index1+1);
int index3=s.find_first_of(" ",index2+1);
int index4=s.find_first_of(".",index3+1);
int index5=s.find_first_of(".",index4+1);
long galleon1=atol(s.substr(0,index1).c_str() );
long sickle1=atol(s.substr(index1+1,index2-index1-1).c_str());
long knut1=atol(s.substr(index2+1,index3-index2-1).c_str());
owe.galleon=galleon1;
owe.sickle=sickle1;
owe.knut=knut1;
long galleon2=atol(s.substr(index3+1,index4-index3-1).c_str());
long sickle2=atol(s.substr(index4+1,index5-index4-1).c_str());
long knut2=atol(s.substr(index5+1,s.length()-index5-1).c_str());
pay.galleon=galleon2;
pay.sickle=sickle2;
pay.knut=knut2;

}//提取命令

Money Knut2Money(long knuts)
{
Money result;
result.knut=abs(knuts%sickle2knut);
result.sickle=abs((knuts/sickle2knut)%galleon2sickle);
result.galleon=knuts/(sickle2knut*galleon2sickle);
return result;

}

Money giveChange(Money owe,Money pay)
{
long knuts1=(owe.galleon*galleon2sickle+owe.sickle)*sickle2knut+owe.knut;
long knuts2=(pay.galleon*galleon2sickle+pay.sickle)*sickle2knut+pay.knut;
return Knut2Money(knuts2-knuts1);
}//找钱还是都统一换算成最小的币种,这样方便运算
ostream& operator << (ostream& out,Money m)
{
out<<m.galleon<<"."<<m.sickle<<"."<<m.knut<<endl;
return out;
}//输出流重载真的太好用了,学习室友代码后果然不一样
int main()
{
string line;
getline(cin,line);
Money owe,pay;
getLine(line,owe,pay);
Money result=giveChange(owe,pay);
cout<<result;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: