ในส่วนนี้เราจะมาดูวิธีการแปลง fmax() และ fmin() ใน C++ fmax() และ fmin() มีอยู่ในไฟล์ส่วนหัว cmath
ฟังก์ชันนี้ใช้ค่าประเภท float หรือ double หรือ long double และคืนค่าสูงสุดหรือต่ำสุดโดยใช้ fmax() และ fmin() ตามลำดับ
หากประเภทอาร์กิวเมนต์แตกต่างกัน เช่น ถ้ามีคนต้องการเปรียบเทียบทศนิยมและสองเท่า หรือลองคู่กับทศนิยม ฟังก์ชันจะพิมพ์เป็นค่านั้นโดยปริยาย แล้วส่งกลับค่าที่สอดคล้องกัน
ตัวอย่าง
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
double res;
//uses of fmax()
res = fmax(50.0, 10.0); //compare for both positive value
cout << fixed << setprecision(4) << "fmax(50.0, 10.0) = " << res << endl;
res = fmax(-50.0, 10.0); //comparison between opposite sign
cout << fixed << setprecision(4) << "fmax(-50.0, 10.0) = " << res << endl;
res = fmax(-50.0, -10.0); //compare when both are negative
cout << fixed << setprecision(4) << "fmax(-50.0, -10.0) = " << res << endl;
//uses of fmin()
res = fmin(50.0, 10.0); //compare for both positive value
cout << fixed << setprecision(4) << "fmin(50.0, 10.0) = " << res << endl;
res = fmin(-50.0, 10.0); //comparison between opposite sign
cout << fixed << setprecision(4) << "fmin(-50.0, 10.0) = " << res << endl;
res = fmin(-50.0, -10.0); //compare when both are negative
cout << fixed << setprecision(4) << "fmin(-50.0, -10.0) = " << res << endl;
} ผลลัพธ์
fmax(50.0, 10.0) = 50.0000 fmax(-50.0, 10.0) = 10.0000 fmax(-50.0, -10.0) = -10.0000 fmin(50.0, 10.0) = 10.0000 fmin(-50.0, 10.0) = -50.0000 fmin(-50.0, -10.0) = -50.0000