2018年5月12日 星期六

itsa60 4計算分數

#include<iostream>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
void replaceD(string &str)
{
int i = 0;
while(i < str.length())
{
if (str[i] == '/' || str[i] == ',')
str[i] = ' ';
i++;
}
}
int gcd(int a1, int a2)
{
while (a1 != a2)
{
if (a1 > a2)
a1 = a1 - a2;
else
a2 = a2 - a1;
}
return a1;
}

int main()
{
int S;
int a1, a2, b1, b2, s1, s2;
string str;
cin >> S;
getline(cin, str);
for (int i = 0; i < S; i++)
{
getline(cin, str);
replaceD(str);
stringstream ss(str);
ss >> a1 >> a2 >> b1 >> b2;
s2 = a2 * b2;
s1 = a1 * b2 + a2 * b1;
cout << s1 / gcd(s1, s2) << "/" << s2 / gcd(s1, s2) << endl;
}
return 0;
}

沒有留言:

張貼留言