Converting between Fahrenheit and Celsius in C [duplicate]

Explicit type conversion is the process of converting a larger data type to a smaller data type. While the C compiler can automatically convert a lower data type to an upper data type, explicit type conversion is required when casting from an upper data type to a lower data type.

Question:

I’m developing a program that converts between Fahrenheit (F) and Celsius (C). Typically, similar programs prompt the user to specify the conversion direction, either from F to C or vice versa, before inputting the data. However, I am aiming to create a more user-friendly version where the user can simply enter the data as “35F” and obtain the desired output.

Currently, I have made significant progress on the program, completing around 70% of it. However, I am encountering difficulties when attempting to read both the Temperature and the character simultaneously in the same

scanf()

. I am curious if it is feasible to accomplish this task in just one line and whether I am on the correct path.

At the moment, the program is functioning smoothly, but the output consistently displays

0.000000

):. I would greatly appreciate your assistance and thank you in advance!

float temperature, Farenheit, Celsius;
char unit0;
char unit1 = 'C';
char unit2 = 'F';
printf("Enter the temperature (Ex. 35F): ");
scanf("%f%c", &temperature, &unit0);
if (unit0 == unit2)
{
    Celsius = (temperature-32) * (5/9) ;
    printf("The temperature %f%c is equal to %f in Celsius", temperature, unit0, Celsius);
}
else
if (unit0 == unit1)
{
    Farenheit = (9/5)*temperature+32;
    printf("The temperature %f%c is equal to %f in Fahrenheit", temperature, unit0, Fahrenheit);
}



Solution:

Replace

(5/9)

with

5.0/9.0

to obtain 0 after rounding when using integer division.

You should do the same for 9/5

Frequently Asked Questions

Posted in Uncategorized