Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

C โปรแกรมบวกเศษส่วนสองส่วน


โดยให้อินพุตเป็นเศษส่วน เช่น 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) {
   // 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 program
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