PAT (Basic Level) 1034 有理数四则运算(模拟)
生活随笔
收集整理的這篇文章主要介紹了
PAT (Basic Level) 1034 有理数四则运算(模拟)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:模擬有理數的四則運算
題目分析:這個題真的考驗代碼實現能力,我模擬了好一會,終于是把樣例過掉了,然后交了一發WA了兩個測試點,一下子想起來如果直接乘的話會爆int,全部改成longlong后又過了一個測試點,最后那個測試點我也不知道為什么,對于每個分數必須先化簡才能繼續操作,不然可能會在某個地方爆掉longlong吧,原理不明
寫這種題的時候一定要保證思路清晰,不能分神,不然一會就不知道自己在寫什么東西了,還有要記得寫注釋,這個題為了盡可能理清思路我把注釋寫的差不多還算可以,然后就是巧用stl(stl重度依賴癥患者表示沒救了),還有就是C++11里很好用的to_string()函數,可以把好多數據類型直接轉換為string類,然后用加號就能連接了,直接上代碼了:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;string change(LL a,LL b) {if(a==0)//特判0return "0";LL gcd=__gcd(abs(a),abs(b));//先化簡a/=gcd;b/=gcd;if(a*b<0)//將負號歸到分子上{a=-abs(a);b=abs(b);}else{a=abs(a);b=abs(b);}string ans;LL k=a/b;if(k)//假分數 {if(b==1)//整數 {if(a>0)//正數{ans+=to_string(k);}else//負數{ans+="(-";ans+=to_string(-k);ans+=")";}}else if(a>0)//正數{ans+=to_string(k);ans+=" ";ans+=to_string(a%b);ans+="/";ans+=to_string(b);}else//負數 {ans+="(-";ans+=to_string(-k);ans+=" ";ans+=to_string(-(a%b));ans+="/";ans+=to_string(b);ans+=")";} }else//真分數 {if(a>0)//正數 {ans+=to_string(a);ans+="/";ans+=to_string(b);}else//負數 {ans+="(-";ans+=to_string(-(a%b));ans+="/";ans+=to_string(b);ans+=")";}}return ans; }string plu(LL a,LL b,LL c,LL d)//加 {return change(a*d+c*b,b*d); }string sub(LL a,LL b,LL c,LL d)//減 {return change(a*d-c*b,b*d); }string mul(LL a,LL b,LL c,LL d)//乘 {return change(a*c,b*d); }string div(LL a,LL b,LL c,LL d)//除 {return change(a*d,b*c); }int main() {LL a,b,c,d;scanf("%lld/%lld %lld/%lld",&a,&b,&c,&d);string ans1=change(a,b);string ans2=change(c,d);printf("%s + %s = %s\n",ans1.c_str(),ans2.c_str(),plu(a,b,c,d).c_str());printf("%s - %s = %s\n",ans1.c_str(),ans2.c_str(),sub(a,b,c,d).c_str());printf("%s * %s = %s\n",ans1.c_str(),ans2.c_str(),mul(a,b,c,d).c_str());if(c)//除法特判printf("%s / %s = %s\n",ans1.c_str(),ans2.c_str(),div(a,b,c,d).c_str());elseprintf("%s / %s = %s\n",ans1.c_str(),ans2.c_str(),"Inf");return 0; }?
總結
以上是生活随笔為你收集整理的PAT (Basic Level) 1034 有理数四则运算(模拟)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 546C So
- 下一篇: PAT (Basic Level) 10