C語言中比較兩個分數的程式


給定兩個分數,分別為分子 nume1 和 nume2,分母為 deno1 和 deno2,任務是比較兩個分數,找出較大的一個。例如,我們有一個分數 1/2 和 2/3,較大的一個是 2/3,因為 1/2 的值是 0.5,而 2/3 的值是 0.66667,後者更大。

輸入 

first.nume = 2, first.deno = 3
second.nume = 4, second.deno = 3

輸出 

4/3

說明 

2/3 = 0.66667 < 4/3 = 1.33333

輸入 

first.nume = 1, first.deno = 2
second.nume = 4, second.deno = 3

輸出 

4/3

用於解決該問題的方法如下

//稍後會寫

演算法

Start
Declare a struct Fraction with elements
   nume, deno
In function Fraction greater(Fraction first, Fraction sec)
   Step 1→ Declare and Initialize t Y = first.nume * sec.deno - first.deno *
sec.nume
   Step 2→ Return (Y > 0) ? first : sec
In function int main()
   Step 1→ Declare Fraction first = { 4, 5 }
   Step 2→Fraction sec = { 3, 4 }
   Step 3→ Fraction res = greater(first, sec)
   Step 4→ Print res.nume, res.deno
Stop

示例

#include <stdio.h>
struct Fraction {
   int nume, deno;
};
// Get max of the two fractions
Fraction greater(Fraction first, Fraction sec){
   //check if the result is in negative then the
   //second fraction is greater else first is greater
   int Y = first.nume * sec.deno - first.deno * sec.nume;
   return (Y > 0) ? first : sec;
}
int main(){
   Fraction first = { 4, 5 };
   Fraction sec = { 3, 4 };
   Fraction res = greater(first, sec);
   printf("The greater fraction is: %d/%d
", res.nume, res.deno);    return 0; }

輸出

如果執行以上程式碼將生成以下輸出 −

The greater fraction is: 4/5

更新於: 13-8-2020

591 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告