Problem Statement
Exercise 1-4: Write a program to print the corresponding Celsius to Fahrenheit table.Solution
This question is to do conversion from Celsius to Fahrenheit. It is opposite to question that was covered K&R Exercise 1.3 Print heading to temperature conversion program.We know the formula for Fahrenheit to Celsius conversion
celsius = (5.0/9.0) * (fahr - 32.0)
Re-arranging the terms in terms of fahr
fahr = (9.0/5.0 * celsius) + 32.0
Re-writing code from K&R Exercise 1.3 Print heading to temperature conversion program we can write program that is:
#include <stdio.h> int main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; celsius = lower; printf(" C F\n"); printf("----------\n"); while(celsius <= upper) { fahr = (9.0/5.0 * celsius) + 32.0; printf("%6.1f %3.0f\n", celsius, fahr); celsius = celsius + step; } return 0; }
Output of the above program is
C F ---------- 0.0 32 20.0 68 40.0 104 60.0 140 80.0 176 100.0 212 120.0 248 140.0 284 160.0 320 180.0 356 200.0 392 220.0 428 240.0 464 260.0 500 280.0 536 300.0 572
Links
Next Article - K&R Exercise 1.5 Temperature conversion reverse orderPrevious Article - K&R Exercise 1.3 Print heading to temperature conversion program
All Article - K & R Answers
Hi there, thanks for the working out of the problem. However you confused F with C in the table header. It should be "printf(" C F\n")".
ReplyDeleteYes you are right. Thanks for correcting me. Hope you find other material interesting also.
Delete