Exercise 1-4 (Celsius to Fahrenheit, temperature)
Chapter_1 Exercise_1-3 | for()_variant Exercise_1-5 |
Exercise 1-4 K&R, p. 13
Exercise 1-4. Write a program to print the corresponding Celsius to Fahrenheit table.
CONTENTS: celsius1.c celsius2.c
celsius1.c download
#include <stdio.h> // for printf()
/*
print Celsius-Fahrenheit table
for celsius = 0, 20, ..., 300
(floating-point version)
*/
int main()
{
float celsius, fahr; // main vars used for output
int lower, upper, step; // vars used for computation
lower = 0; // lower limit of temperature table
upper = 300; // upper limit
step = 20; // step size
printf("Celsius-Fahrenheit\n");
printf("conversion table\n");
printf("------------------------\n");
celsius = lower;
while(celsius <= upper)
{
fahr = (9.0 / 5.0) * celsius + 32.0;
printf("%3.0f %6.1f\n", celsius, fahr);
celsius += step; // celsius = celsius + step;
}
}
/*
gcc celsius1.c -o celsius1
./celsius1
Celsius-Fahrenheit
conversion table
------------------------
0 32.0
20 68.0
40 104.0
60 140.0
80 176.0
100 212.0
120 248.0
140 284.0
160 320.0
180 356.0
200 392.0
220 428.0
240 464.0
260 500.0
280 536.0
300 572.0
*/
Note: (9.0 / 5.0) multiplied with a multiple of 10 gives an integer, but we should keep celsius and fahr as float variables for computations. In order to get similar results as before, we can choose the interval -20...150 and the step 10.
celsius2.c download
#include <stdio.h> // for printf()
/*
print Celsius-Fahrenheit table
for celsius = -20, -10, 0, 10, ..., 150
(floating-point version)
*/
int main()
{
float celsius, fahr; // main vars used for output
int lower, upper, step; // vars used for computation
lower = -20; // lower limit of temperature table
upper = 150; // upper limit
step = 10; // step size
printf("Celsius-Fahrenheit\n");
printf("conversion table\n");
printf("------------------------\n");
celsius = lower;
while(celsius <= upper)
{
fahr = (9.0 / 5.0) * celsius + 32.0;
printf("%3.0f %6.0f\n", celsius, fahr);
celsius += step; // celsius = celsius + step;
}
}
/*
gcc celsius2.c -o celsius2
./celsius2
Celsius-Fahrenheit
conversion table
------------------------
-20 -4
-10 14
0 32
10 50
20 68
30 86
40 104
50 122
60 140
70 158
80 176
90 194
100 212
110 230
120 248
130 266
140 284
150 302
*/
Chapter_1 Exercise_1-3 | BACK_TO_TOP | for()_variant Exercise_1-5 |
Comments
Post a Comment