• PAT Advanced 1081 Rational Sum (20) [数学问题-分数的四则运算]


    题目

    Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum.
    Input Specification:
    Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers “a1/b1 a2/b2 …” where all the numerators and denominators are in the range of “long int”. If there is a negative number, then the sign must appear in front of the numerator.
    Output Specification:
    For each test case, output the sum in the simplest form “integer numerator/denominator” where “integer” is the integer part of the sum, “numerator” < “denominator”, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.
    Sample Input 1:
    5
    2/5 4/15 1/30 -2/60 8/3
    Sample Output 1:
    3 1/3
    Sample Input 2:
    2
    4/3 2/3
    Sample Output 2:
    2
    Sample Input 3:
    3
    1/3 -1/6 1/8
    Sample Output 3:
    7/24

    题目分析

    给出N有理数,格式为分子/分母,若为负,则负号一定在分子前。求N个有理数的和

    解题思路

    1. 输入分子、分母,化简
    2. 计算累加分数和与下一个分数和,化简
    3. 累加完成后,假分数转换为真分数,打印整数部分和分式部分

    易错点

    1. 若和为0,要输出“0”(否则测试点4错误)

    知识点

    1. long long类型的数据输入/输出
      输入:scanf("%lld",&n);
      输出:printf("%lld",n);

    Code

    Code 01

    #include <iostream>
    using namespace std;
    // 求公约数
    int gcd(long long a, long long b) {
    	return b==0?abs(a):gcd(b, a%b);
    }
    // 化简分式
    void reduction(long long &a, long long &b) {
    	int gcdvalue = gcd(a,b);
    	a /= gcdvalue;
    	b /= gcdvalue;
    }
    int main(int argc,char * argv[]) {
    	long long n,a,b,suma=0,sumb=1,gcdvalue;
    	scanf("%lld",&n);
    	for(int i=0; i<n; i++) {
    		scanf("%lld/%lld",&a,&b);
    		reduction(a,b);
    		suma=a*sumb+suma*b;
    		sumb=b*sumb;
    		reduction(suma,sumb);
    	}
    	long long itg = suma/sumb;
    	suma = suma-(sumb*itg);
    	if(itg!=0) {
    		printf("%lld",itg);
    		if(suma!=0)printf(" ");
    	}
    	if(suma!=0)printf("%lld/%lld",suma,sumb);
    	if(itg==0&&suma==0)printf("0");
    	return 0;
    }
    
  • 相关阅读:
    jQuery 自执行函数
    IRelationalOperator空间关系接口简介
    9.2 空间拓扑运算[转]
    解决关于ArcGIS10.2服务手动启动的问题
    Multipart to single part feature
    Multipart polyline to single part lines
    VS2015 C#6.0 中的没有实现/支持的特性
    VS2015 C#6.0 中的那些新特性
    ArcGIS中各种合并要素(Union、Merge、Append、Dissolve)的异同点分析 转载
    FME2010 案例分析: 动态批量转换
  • 原文地址:https://www.cnblogs.com/houzm/p/12261856.html
Copyright © 2020-2023  润新知