给定输入作为分数,即a / b和c / d,其中a,b,c和d可以是除0以外的任何整数值,任务是将这两个分数相加以生成其最终和。
分数用-表示
a / b,其中a称为分子,b称为分母。
a和b可以具有任何数值,但b可以具有除0之外的任何数值。
两个分数的和表示为a / b + c / d,将两个项相加的规则是它们的分母必须相等,如果它们不相等,则应使它们相等,然后只能执行加法。
Input-: 1/4 + 2/12 Output-: 5/12 Since both the fractions denominators are unequal so to make them equal either GCD or LCM can be calculated. So in this case by multiplying the denominator which is 4 by 3 we can make them equal (1 * 3) / (4 * 3) = 3 / 12 Add both the terms: 3 / 12 + 2 / 12 = 5 / 12 Input-: 1/4 + 2/4 Output-: 3/4 Since both the terms have same denominator they can be directly added
In function int gcd(int a, int b) Step 1-> If a == 0 then, return b Step 2-> Return gcd(b%a, a) In function void smallest(int &den3, int &n3) Step 1-> Declare and initialize common_factor as gcd(n3,den3) Step 2-> Set den3 = den3/common_factor Step 3-> Set n3 = n3/common_factor In Function void add_frac(int n1, int den1, int n2, int den2, int &n3, int &den3) Step 1-> Set den3 = gcd(den1,den2) Step 2-> Set den3 = (den1*den2) / den3 Step 3-> Set n3 = (n1)*(den3/den1) + (n2)*(den3/den2) Step 4-> Call function smallest(den3,n3) In Function int main() Step 1-> Declare and initialize n1=1, den1=4, n2=2, den2=12, den3, n3 Step 2-> Call add_frac(n1, den1, n2, den2, n3, den3) Step 3-> Print the values of n1, den1, n2, den2, n3, den3
#include <stdio.h> int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } void smallest(int &den3, int &n3) { //查找两个词的gcd- int common_factor = gcd(n3,den3); den3 = den3/common_factor; n3 = n3/common_factor; } void add_frac(int n1, int den1, int n2, int den2, int &n3, int &den3) { //找到den1和den2的gcd- den3 = gcd(den1,den2); //LCM * GCD = a * b- den3 = (den1*den2) / den3; //将输入更改为具有相同的分母 //获得的最终分数的分子 n3 = (n1)*(den3/den1) + (n2)*(den3/den2); smallest(den3,n3); } //驱动程序 int main() { int n1=1, den1=4, n2=2, den2=12, den3, n3; add_frac(n1, den1, n2, den2, n3, den3); printf("%d/%d + %d/%d = %d/%d\n", n1, den1, n2, den2, n3, den3); return 0; }
输出结果
1/4 + 2/12 = 5/12