用 while 迴圈編寫一個 C 程式以將任意分數化簡


將分數化簡為最低項意味著除了 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
");       break;    }    while(mod!=0){       mod= x % y;       x=y;       y=mod;    }    lessnumert= numerat/x;    lessdenomi=denomi/x;    printf("lowest representation of fraction:%d/%d
",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
", num1?"Infinity":"0");    }    while (GCD > 1) {       if (num1 % GCD == 0 && num2 % GCD == 0)          break;       GCD--;    }    printf("Final fraction %d/%d
", num1 / GCD, num2 / GCD);    return 0; }

輸出

Enter the value for num1 /num2:28/32
Final fraction 7/8

更新時間: 05-Mar-2021

1K + 次瀏覽

開啟你的 事業

完成課程認證

開始學習
廣告
© . All rights reserved.