1034 有理数四则运算 (20分)
https://pintia.cn/problem-sets/994805260223102976/problems/994805287624491008
本题代码:
#include <iostream> #include <cmath> #include <algorithm> #include <cstdio> #include <string> #include <cstring> typedef long long ll; using namespace std; ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } string print(ll a,ll b) { ll k=gcd(a,b); a=a/k;b=b/k; if(a==0) return "0"; string s; int flag=0; if(b<0) {a=-a;b=-b;} if(a<0) {s.append("(-");a=-a;flag=1;} if(a>=b) s.append(to_string(a/b)); if(a>=b&&a%b) s.insert(s.end(),' '); a=a%b; if(a) { s.append(to_string(a)); s.insert(s.end(),'/'); s.append(to_string(b)); } if(flag) s.insert(s.end(),')'); return s; } int main() { ll a1,a2,b1,b2; char chr='/'; cin>>a1>>chr>>b1; cin>>a2>>chr>>b2; cout<<print(a1,b1)<<" + "<<print(a2,b2)<<" = "<<print(a1*b2+a2*b1,b1*b2)<<endl; cout<<print(a1,b1)<<" - "<<print(a2,b2)<<" = "<<print(a1*b2-a2*b1,b1*b2)<<endl; cout<<print(a1,b1)<<" * "<<print(a2,b2)<<" = "<<print(a1*a2,b1*b2)<<endl; if(b1*a2) cout<<print(a1,b1)<<" / "<<print(a2,b2)<<" = "<<print(a1*b2,b1*a2)<<endl; else cout<<print(a1,b1)<<" / "<<print(a2,b2)<<" = Inf "; return 0; }
知识点:string::append http://www.cplusplus.com/reference/string/string/append/
// appending to string #include <iostream> #include <string> int main () { std::string str; std::string str2="Writing "; std::string str3="print 10 and then 5 more"; // used in the same order as described above: str.append(str2); // "Writing " str.append(str3,6,3); // "10 " str.append("dots are cool",5); // "dots " str.append("here: "); // "here: " str.append(10u,'.'); // ".........." str.append(str3.begin()+8,str3.end()); // " and then 5 more" str.append<int>(5,0x2E); // "....." std::cout << str << ' '; return 0; } //Output: //Writing 10 dots here: .......... and then 5 more.....