ได้รับสองเศษส่วนที่มีตัวเศษ 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
ประกาศ struct Fraction มีสมาชิก
nume, deno
In function Fraction greater(Fraction first, Fraction sec)
Step 1: ประกาศและกำหนด Y = first.nume * sec.deno - first.deno * sec.nume
Step 2: Return (Y > 0) ? first : sec
In function int main()
Step 1: ประกาศ 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;
};
// หาเศษส่วนที่มากกว่าของสองเศษส่วน
Fraction greater(Fraction first, Fraction sec) {
// ตรวจสอบถ้าผลลัพธ์เป็นลบ แล้วเศษส่วนที่สองมากกว่า ไม่งั้นตัวแรกมากกว่า
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("เศษส่วนที่มากกว่าคือ: %d/%d\n", res.nume, res.deno);
return 0;
}
ผลลัพธ์
หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ —
เศษส่วนที่มากกว่าคือ: 4/5