ลดเศษส่วนให้เหลือเทอมที่ต่ำที่สุด หมายความว่าไม่มีตัวเลขใดๆ ยกเว้น 1 ที่สามารถแบ่งออกได้ทั้งตัวเศษและส่วนเท่าๆ กัน
ตัวอย่างเช่น 24/4 เป็นเศษส่วน เทอมที่ต่ำที่สุดสำหรับเศษส่วนนี้คือ 6 หรือ 12/16 เป็นเศษส่วน เทอมที่ต่ำที่สุดคือ 3/4
ตอนนี้ มาเขียนโปรแกรม c เพื่อลดเศษส่วนให้เหลือเทอมต่ำสุดกัน
ตัวอย่างที่ 1
#include<stdio.h>
int main(){
int x,y,mod,numerat,denomi,lessnumert,lessdenomi;
printf("enter the fraction by using / operator:");
scanf("%d/%d", &x,&y);
numerat=x;
denomi=y;
switch(y){
case 0:printf("no zero's in denominator\n");
break;
}
while(mod!=0){
mod= x % y;
x=y;
y=mod;
}
lessnumert= numerat/x;
lessdenomi=denomi/x;
printf("lowest representation of fraction:%d/%d\n",lessnumert,lessdenomi);
return 0;
} ผลลัพธ์
enter the fraction by using / operator:12/24 lowest representation of fraction:1/2
ตัวอย่าง
//reduce the Fraction
#include <stdio.h>
int main() {
int num1, num2, GCD;
printf("Enter the value for num1 /num2:");
scanf("%d/%d", &num1, &num2);
if (num1 < num2){
GCD = num1;
} else {
GCD = num2;
}
if (num1 == 0 || num2 == 0){
printf("simplified fraction is %s\n", num1?"Infinity":"0");
}
while (GCD > 1) {
if (num1 % GCD == 0 && num2 % GCD == 0)
break;
GCD--;
}
printf("Final fraction %d/%d\n", num1 / GCD, num2 / GCD);
return 0;
} ผลลัพธ์
Enter the value for num1 /num2:28/32 Final fraction 7/8