
给定输入为分数,即 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/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 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程序:两个分数相加的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444148.html
微信扫一扫
支付宝扫一扫