First code:
#include <stdio.h>
int main() {
int Celsius;
printf("temperature in Celsius?\n");
scanf("%d", &Celsius);
float Fahrenheit = (Celsius * 9 / 5) 32;
printf("temperature in Fahrenheit is %f", Fahrenheit);
return 0;
}
Second code:
#include <stdio.h>
int main() {
float Celsius;
printf("temperature in Celsius?\n");
scanf("%f", &Celsius);
float Fahrenheit = (Celsius * 9 / 5) 32;
printf("temperature in Fahrenheit is %f", Fahrenheit);
return 0;
}
I want to convert celsius to Fahrenheit, but the problem is if I put celsius=37:
First code shows 98.00000 (which is a wrong answer) while the second code shows 98.599998 (which is correct).
CodePudding user response:
When Celsius is declared of type int, this this expression
(Celsius * 9/5) 32;
that doesn't involve any floating point variables is computed entirely in integer space. Integer division in code basically means "drop the remainder". (e.g. 9/5 == 1)
Easy fix is to force at least one variable or constant in that expression to be a floating point type.
float Fahrenheit = (Celsius * 9.0f/5) 32;
Or just simply:
float Fahrenheit = (Celsius * 1.8f) 32;
CodePudding user response:
If Celsius is defined as an int (as in the first program), the expression (Celsius * 9 / 5) 32; is computed using integer arithmetics, hence the division by 5 is rounded toward 0. Making Celcius a float allows for entry of decimal values such as 19.5 and performs the computation using floating point arithmetics, giving the expected result, which should really be 98.6, but shows as 98.599998 because of the limited precision of type float and the default number of decimals (6).
Here is a modified version:
#include <stdio.h>
int main() {
double Celsius;
printf("temperature in Celsius?\n");
if (scanf("%lf", &Celsius) == 1) {
double Fahrenheit = (Celsius * 9.0 / 5) 32;
printf("temperature in Fahrenheit is %g\n", Fahrenheit);
}
return 0;
}
CodePudding user response:
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
/* Input temperature in celsius */
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
/* celsius to fahrenheit conversion formula */
fahrenheit = (celsius * 9 / 5) 32;
printf("%.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);
return 0;
}
