ให้เศษส่วนสองส่วนที่มีตัวเศษ 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\n", res.nume, res.deno);
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
The greater fraction is: 4/5