Search code examples
cdata-conversiontemperature

Converting from Fahrenheit to Celsius and viceversa in C


I'm working on a program to convert F to C and vice-versa. The thing is, I've seen similar programs where you first enter if the conversion is from degree F to degree C or vice-versa, and then you Enter the data. I just want kind of a more user friendly version, where you Enter the data as "35F" and it gives you output.

So far I have basically %70 of the program done but I think I'm having problems when reading the Temperature and the character together in the same scanf(). I was wondering if it is possible to do that in just 1 line and if I'm aiming in the right directions.

Currently the program is running fine but the Output is always 0.000000 ): I would love your help and thank your 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

  • change (5/9) to 5.0/9.0. If you use integer division, this gives you 0 after rounding.

    You should do the same for 9/5