การแปลงอุณหภูมิ คือการแปลงอุณหภูมิฟาเรนไฮต์เป็นเซลเซียส หรือ เซลเซียสเป็นฟาเรนไฮต์
ในการเขียนโปรแกรมนี้ เราจะอธิบายวิธีแปลงอุณหภูมิฟาเรนไฮต์เป็นเซลเซียส และแสดงในรูปตาราง โดยใช้ฟังก์ชัน
ตัวอย่าง
โปรแกรม C สำหรับการแปลงอุณหภูมิ:
#include <stdio.h>
float conversion(float);
int main() {
float fh, cl;
int begin = 0, stop = 300;
printf("Fahrenheit \t Celsius\n"); // หัวตาราง
printf("----------\t-----------\n");
fh = begin;
while(fh <= stop) {
cl = conversion(fh); // เรียกฟังก์ชัน
printf("%3.0f\t\t%6.1f\n", fh, cl);
fh = fh + 20;
}
return 0;
}
float conversion(float fh) { // ฟังก์ชันที่ถูกเรียก
float cl;
cl = (fh - 32) * 5 / 9;
return cl;
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
Fahrenheit Celsius ---------- ----------- 0 -18 20 -7 40 4 60 16 80 27 100 38 120 49 140 60 160 71 180 82 200 93 220 104 240 116 260 127 280 138 300 149
ด้วยวิธีเดียวกัน สามารถเขียนโปรแกรมแปลงเซลเซียสเป็นฟาเรนไฮต์ได้
เพียงแค่เปลี่ยนสมการเป็น:
Fahrenheit = (Celsius * 9 / 5) + 32