分数用 − 表示
a / b,其中 a 被称为分子,b 被称为分母。a 和 b 可以有任何数值,但 b 不能为 0。两个分数的和表示为 a / b + c / d,添加这两个项的规则是它们的分母必须相等,如果它们不相等,则应使它们相等,然后才能进行相加。示例input-: 1/4 + 2/12output-: 5/12since 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 / 12add both the terms: 3 / 12 + 2 / 12 = 5 / 12input-: 1/4 + 2/4output-: 3/4since 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 bstep 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_factorin 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
example的中文翻译为:示例#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) { // finding gcd of both terms 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) { // to find the gcd of den1 and den2 den3 = gcd(den1,den2); // lcm * gcd = a * b den3 = (den1*den2) / den3; // changing the inputs to have same denominator // numerator of the final fraction obtained n3 = (n1)*(den3/den1) + (n2)*(den3/den2); smallest(den3,n3);}// driver programint 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
", n1, den1, n2, den2, n3, den3); return 0;}
输出1/4 + 2/12 = 5/12
以上就是c程序:两个分数相加的详细内容。
