ch1-Temperature Programs

Chapter_1     Exercise_1-2     quotes Truncate     Exercise_1-3







CONTENTS:     temp.c     Right-justified     tempf.c




temp.c     K&R, p. 9     (Fahrenheit-Celsius)     download


#include <stdio.h> // for printf()

/*
print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300
*/

int main()
{
int fahr, celsius; // 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

fahr = lower;
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr += step; // fahr = fahr + step;
}
}
/*
gcc temp.c -o temp
./temp
0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148
*/












tempr.c         download


#include <stdio.h> // for printf()

/*
print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300
*/

int main()
{
int fahr, celsius; // 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

fahr = lower;
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%3d\t%3d\n", fahr, celsius);
fahr += step; // fahr = fahr + step;
}
}
/*
gcc tempr.c -o tempr
./tempr
0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148
*/











tempf.c     K&R, p. 12     (floating-point version)     download


#include <stdio.h> // for printf()

/*
print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300
(floating-point version)
*/

int main()
{
float fahr, celsius; // 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

fahr = lower;
while(fahr <= upper)
{
celsius = (5.0 / 9.0) * (fahr-32.0);
printf("%3.0f %6.1f\n", fahr, celsius);
fahr += step; // fahr = fahr + step;
}
}
/*
gcc tempf.c -o tempf
./tempf
0 -17.8
20 -6.7
40 4.4
60 15.6
80 26.7
100 37.8
120 48.9
140 60.0
160 71.1
180 82.2
200 93.3
220 104.4
240 115.6
260 126.7
280 137.8
300 148.9
*/





Note:  In the previous programs (temp.c, Right-justified), the Celsius values have been truncated to the lower integer value (see also Truncate).









Chapter_1     Exercise_1-2     quotes BACK_TO_TOP Truncate     Exercise_1-3



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo