Reputation: 229
Originally there was a problem to Fahrenheit to Celsius for multiple values of Fahrenheit. Now in problem 1-15 we have to use a function for this task. Following is my code:
#include<stdio.h>
float temp_conv(float n);
int main()
{
float lower, upper, step;
int i;
lower= 0;
upper= 300;
step= 20;
for(i=0; i<=(upper-lower)/step; ++i)
printf("%5.1f\t%6.2f\n", i*step, temp_conv(i*step));
}
float temp_conv(float n)
{
float fahr, celsius;
celsius= (5.0/9.0)*(fahr-32.0);
return celsius;
}
And is producing the following output:
0.0 -17.78
20.0 -17.78
40.0 -17.78
60.0 -17.78
80.0 -17.78
100.0 -17.78
120.0 -17.78
140.0 -17.78
160.0 -17.78
180.0 -17.78
200.0 -17.78
220.0 -17.78
240.0 -17.78
260.0 -17.78
280.0 -17.78
300.0 -17.78
I am passing different values in function temp_conv, but then too it is producing the converted value of 0 Fahrenheit. Maybe there is some problem with the function, but then how it is computing the Celsius value for 0 Fahrenheit?
Please help.
Upvotes: 0
Views: 45
Reputation: 141235
float temp_conv(float n) {
float fahr, celsius;
celsius = (5.0/9.0)*(fahr-32.0);
return celsius;
}
You ignore the argument n
that you passed to the function and calculate celsius
from fahr
. fahr
is uninitialized (there is no fahr = something
), it is having some uninitialized garbage value that just so happens to result in -17.78
.
Just calculate it from the argument instead:
float temp_conv(float n) {
float celsius;
celsius = (5.0 / 9.0) * (n - 32.0);
return celsius;
}
or with better naming:
float temp_conv(float fahr) {
float celsius;
celsius = (5.0 / 9.0) * (fahr - 32.0);
return celsius;
}
or really just:
float temp_conv(float fahr) {
return (5.0 / 9.0) * (fahr - 32.0);
}
Upvotes: 3