N个数求和(PTA)

这题多输出了一个空格,卡了半天。。。

leetcode刷多了,后遗症

这题可以用scanf("%lld/%lld"),直接读入,不过我用了stoll,也就是stoi,string to int ,把string转int

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+10;

void getNum(long long& s,long long& f,string num) {
    long long i=0;
    for (auto c:num) {
        if (c=='/') {
            break;
        }
        i++;
    }
    string pre=num.substr(0,i);
    string suf=num.substr(i+1);
    s=stoll(pre);
    f=stoll(suf);
    // cout<<s<<endl<<f<<endl;
}

long long gcd(long long a,long long b) {
	return a%b==0?b:gcd(b,a%b);
}

void toEasy(long long& s,long long& f) {
	long long g=abs(gcd(s,f));
	s/=g;
	f/=g;
}

int main() {
//    freopen("in.txt","r",stdin);
    long long n;
    cin>>n;
    cin.get();
    string line;
    getline(cin,line);
    stringstream ss(line);
    string num;
    long long s1=0,f1=1,s2,f2;
    while (ss>>num) {
        getNum(s2,f2,num);
        s1*=f2;
        s2*=f1;
        s1+=s2;
        f1*=f2;
        toEasy(s1,f1);
    }
    toEasy(s1,f1);
    long long pre=s1/f1;
    s1%=f1;
    if (pre) {
        cout<<pre;
    }
	if (pre&&s1) {
		cout<<" ";
	}
	//¶àÁËÒ»¸ö¿Õ¸ñ¾Í»á´í 
    if (pre==0&&s1<0) {
    	cout<<"-";
	}
    if (s1) {
        printf("%d/%d",abs(s1),f1);
    }
    if (pre==0&&s1==0) {
        printf("0");
    }
    printf("
");
    return 0;
}
/*
1
1/2 1/2 1/2 1/2
3
-1/2 -1/2 -1/2
*/
原文地址:https://www.cnblogs.com/xyqxyq/p/12300332.html