Pages - Menu

Thursday 1 November 2012

Converting temperature in C

Celsius to Fahrenheit

The following C function receives a temperature in degrees Celsius and returns the equivalent temperature in  Fahrenheit.
/*
 * Description:
 *  Converts temperature from Celsius to Fahrenheit
 * Parameters:
 *  celsiusTemperature - temperature in degrees Celsius to be converted
 * Returns:
 *  fahrenheitTemperature - the equivalent temperature in the Fahrenheit scale
 */
float CelsiusToFahrenheit(float celsiusTemperature)
{
    float fahrenheitTemperature = celsiusTemperature*9/5+32;
    return fahrenheitTemperature;
}

Fahrenheit to Celsius

The following C function receives a temperature in degrees Fahrenheit and returns the equivalent temperature in Celsius.
/*
 * Description:
 *  Converts temperature from Fahrenheit to Celsius
 * Parameters:
 *  fahrenheitTemperature - temperature in degrees Fahrenheit to be converted
 * Returns:
 *  celsiusTemperature - the equivalent temperature in the Celsius scale
 */
float FahrenheitToCelsius(float fahrenheitTemperature)
{
    float celsiusTemperature = (fahrenheitTemperature-32)*5/9;
    return celsiusTemperature;
}

Example:

This C program takes your option and uses one of the functions above in accordance to your choice to convert the given temperature from one scale to the other.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

float CelsiusToFahrenheit(float celsiusTemperature);
float FahrenheitToCelsius(float fahrenheitTemperature);

int main(void)
{
    float celsiusTemperature = 0, fahrenheitTemperature = 0;
    int option = 0, exit = 0;
    while (exit == 0)
    {
        system("cls");
        printf("\n Choose your option: "
               "\n\t[1] Convert Celsius to Fahrenheit"
               "\n\t[2] Convert Fahrenheit to Celsius"
               "\n\t[0] Exit the program\n");
        scanf("%d",&option);
        switch (option)
        {
        case 1:
            printf("\n Enter the temperature in degrees Celsius: ");
            scanf("%f",&celsiusTemperature);
            fahrenheitTemperature = CelsiusToFahrenheit(celsiusTemperature);
            printf(" The equivalent in Fahrenheit is: %.1f",
                   fahrenheitTemperature);
            getch();
            break;
        case 2:
            printf("\n Enter the temperature in degrees Fahrenheit: ");
            scanf("%f",&fahrenheitTemperature);
            celsiusTemperature = FahrenheitToCelsius(fahrenheitTemperature);
            printf(" The equivalent in Celsius is: %.1f",celsiusTemperature);
            getch();
            break;
        case 0:
            exit = 1;
            break;
        default:
            printf("\n Enter again.");
            getch();
            break;
        }
    }
    getch();
    return 0;
}
Output: