pta addition of rational numbers

This question requires writing a program to calculate the sum of two rational numbers.

Input format:

a1/b1 a2/b2The input gives two rational numbers in the form of fractions on one line in the form of , where the numerator and denominator are both positive integers in the integer range.

Output format:

Print the sum of two rational numbers on one line in the format of a/b. Note that it must be the simplest fractional form of the rational number. If the denominator is 1, only the numerator will be output.

Input sample 1:

1/3 1/6

Output sample 1:

1/2

Input sample 2:

4/3 2/3

Output sample 2:

2

Specific code:

#include<iostream>
using namespace std;

int main(){
    int a1, b1, a2, b2, re1, re2, min, key;
    scanf("%d/%d%d/%d",&a1,&b1,&a2,&b2);//输入
    
    //约分求和 
    a1 = a1 * b2; 
	a2 = a2 * b1;
	re1 = a1 + a2;//分子
	re2 = b1 * b2;//分母

    min = (re1 < re2)?re1:re2;
    for(int i = 2;i <= min;i++){
        if(re1 % i == 0 && re2 % i == 0){
            key = i;
        }
    }

    if(key >= 0){
        re1 /= key;
        re2 /= key;
    }

    if(re2 != 1){
        cout<<re1<<"/"<<re2;
    }else{
        cout<<re1;
    }

}

Guess you like

Origin blog.csdn.net/weixin_51890646/article/details/125958299